6 个无人传授的 Python 技巧和窍门

2025-05-28

6 个无人传授的 Python 技巧和窍门

Python 目前是世界上使用最广泛的编程语言,其独特原因是 Python 开发人员乐于用它来构建软件。

其简单的语法、大量的库和快速的学习曲线赢得了初学者和经验丰富的开发人员的青睐。

所以今天我将分享 6 个通常不会教的 Python 技巧。😃

所有示例都位于此Github repo上,订阅后即可使用,因此请务必查看它们。

-->在此处访问并下载本文的源代码


 

🎉赠品⚡

我们正在 Udemy 上免费赠送您所需的任何课程。课程价格不限。
参与方式如下:

  1. 👍 回复此帖
  2. ✉️ 订阅我们的新闻通讯<--非常重要

 


从序列中选择一个随机元素

标准库中的这个random包有很多有用的函数。但random.choice(seq)有一个特别有用。

它允许您从可索引序列中选择一个随机元素,例如lists,,,tuples甚至strings

import random as r
my_list = [1, 2, 3, "go"]
print(r.choice(my_list))

# Random item
Enter fullscreen mode Exit fullscreen mode

实际例子

接收书籍序列的书籍选择器函数会进行随机选择,从列表中删除该项目,并以字符串形式返回该选择

# We import only the function we need
from random import choice

def book_picker(books):
    book_choice = choice(books)
    books.remove(book_choice)    
    return f"You picked {book_choice}"

books = ["Harry potter", "Don Quixote", "Learn Python by Daniel Diaz", "Dracula"]

print(book_picker(books)) # Random choice

print(books) # Remaining books
Enter fullscreen mode Exit fullscreen mode

限制与例外

如果您尝试在不可索引的序列中使用random.choice(seq),例如dictionaries,,setsnumeric types,Python 将引发错误。

# With Dictionary
import random as r
scores = {"Jhon": 4, "Ben": 3, "Diana": 5}

print(r.choice(my_scores)) # Key error
Enter fullscreen mode Exit fullscreen mode

此外,如果序列为空,Python 将引发IndexError

# With an empty sequence
import random as r
empty_list = []

print(r.choice(empty_list)) # Index error
Enter fullscreen mode Exit fullscreen mode

解包元素*

有时我们需要打印用空格分隔的可迭代元素,我见过的最常见的解决方案是

my_list = [1, 2, 3, 5, 7]

for i in my_list:
   print(i, end=" ") # 1 2 3 5 7 
Enter fullscreen mode Exit fullscreen mode

虽然这解决了问题,但代码不太符合Python 风格。还有一个更简单的解决方案,使用解包运算符“*”

my_list = [1, 2, 3, 5, 7]

print(*mylist) # 1 2 3 5 7 
Enter fullscreen mode Exit fullscreen mode

正如您所看到的,解包运算符始终设置在可迭代对象的左侧,它告诉 Python:

将此可迭代对象中的每个元素分配给所需的元组或列表

记住,可迭代对象是指任何可以用 for 循环迭代的序列。如果你想检查某个数据类型是否可迭代,请使用该iter()函数。


print(iter("This is a string")) # Str Iterable object

print(iter(["this", "is", "a", "list"])) # List iterable object

print(iter(1))
# Raises an error
# Integers can't be iterated
Enter fullscreen mode Exit fullscreen mode

使用变量解包

了解了拆包运算符的强大功能后,你或许会想用它来将数据存储在变量中。那么,让我们看看如何操作。


string = "Let's learn Python"

# We want to assign the unpacked result in var1
var1 = [*string]

print(var1)
# ['L', 'e', 't', "'", 's', ' ', 'l', 'e', 'a', 'r', 'n', ' ', 'P', 'y', 't', 'h', 'o', 'n']
Enter fullscreen mode Exit fullscreen mode

[*iterable]部分可能看起来令人困惑,所以让我解释一下。

当我们解包一个可迭代对象时,python 需要一些数据结构来存储该可迭代对象的每个元素,因此我们在运算符[]之外创建了一个列表()*

如果我们尝试获取由运算符产生的变量的类型,*我们会得到

another_str = "The * operator"

# Using a list outside the unpacking
var2 = [*another_str]

print(type(var2)) # List

# Using a tuple
# Tuples ends with a comma
var3 = (*another_str,)

print(type(var3)) # Tuple
Enter fullscreen mode Exit fullscreen mode

当然,如果你尝试在外面没有列表或元组的情况下解包,你会得到一个SyntaxError

bad_variable = *"Bad String"
# Syntax error
Enter fullscreen mode Exit fullscreen mode

拆包还有更多用途,我可以写一篇关于它的独家文章。😀

用于set优化操作

根据python 文档,该类set(iterable)从可迭代对象创建一个集合对象。

你们中的一些人可能知道集合是一种无序的数据结构(因此不可索引),它的特点之一是不允许重复的项目。

实际例子

删除重复项并返回排序列表的函数。

def eliminate_duplicates(lst):
    """
    Returns a sorted list, without duplicates
    """ 
    new_list = list(set(lst)) 

    new_list.sort()    

    return new_list

list1 = [25, 12, 11, 4, 12, 12, 25]

print(eliminate_duplicates(list1))
Enter fullscreen mode Exit fullscreen mode

无需退出编辑器即可查看类的属性和方法

dir()函数返回类的属性和方法。我们可以利用这个有用的技巧来列出类类型中的所有定义。

-> $ python 
string = "A string"

print(dir(string))

# ['__add__', .....,'upper', 'zfill']
Enter fullscreen mode Exit fullscreen mode

例如,如果我们正在寻找一种将字符串转换为大写的字符串方法,而我们又懒得打开浏览器,那么我们只需dir以字符串作为参数运行该函数并搜索正确的方法

实际例子

我们能得到的最佳方法dir是使用第三方包,我们可以从类中获取我们需要的所有信息,而无需退出终端

-> $ python


from django.views import View

print(dir(View))

# ['__class__', '__delattr__', .... 'setup']
Enter fullscreen mode Exit fullscreen mode

切片操作

切片只是访问序列特定部分的一种方式。在 Python 中,切片可以让我们实现多种功能。

反转序列

# Reversing lists
lst = ["Fun", "is", "Programming"]

lst = lst[::-1]

print(lst) # ['Programming', 'is', 'Fun']

# Reversing strings

string = "Dog running on the park"

string = string[::-1]

print(string) # krap eht no gninnur goD
Enter fullscreen mode Exit fullscreen mode

实际例子

返回直到给定索引的序列的函数

def cutoff(seq, index):
    if not len(seq) > index:
        return "Sorry the index is bigger than the sequence"

    return seq[:index]

long_string = "This is a long description of a blog post about Python and technology"

print(cutoff(long_string, 15))
# This is a long 

print(cutoff(long_string, 70))
# Sorry the index is bigger than the sequence
Enter fullscreen mode Exit fullscreen mode

用 10 个字母调用调试器

该函数breakpoint从 Python 3.6 及以上版本开始可用。这将调用 的会话pdb.set_trace()

这听起来可能纯粹是为了方便(也许确实如此),但对我来说,这是一种调用调试器的非常简短而优雅的方式

例子

n_odds = 0

for i in range(1, 14, 2):
    # Check for the value of i in each iteration
    breakpoint()
    # Bad condition
    if i % 2 == 0:
        n_odds += 1

print(n_odds)
Enter fullscreen mode Exit fullscreen mode

图像

结论

在本教程中,您学习了:

  • 从序列中选择一个随机元素
  • 使用运算*符解包元素
  • 集合有效删除重复项的能力
  • 如何在不退出代码编辑器的情况下搜索方法和变量
  • Python切片的多种用途
  • 如何使用函数调用调试器breakpoint

请考虑在Ko-fi上支持我。这将帮助我继续构建这些教程!
科菲

如果您有任何反馈,请在评论中告诉我!


另请阅读:

文章来源:https://dev.to/worldindev/6-python-tips-tricks-that-no-one-teaches-4j73
PREV
ES6 速查表 🔥 - 你所需要的一切🚀
NEXT
25 门值得你花钱和花时间的 Udemy 课程