10个你可能没听说过的隐藏的Python宝石

360影视 动漫周边 2025-03-20 10:29 5

摘要:Python是一种强调简单性和可读性的语言,但在其干净的语法之下,隐藏着一个强大的、鲜为人知的特性的宝库。许多开发人员,即使是经验丰富的开发人员,也经常忽略其中的一些gem,这些gem可以帮助简化代码,提高效率,并使编程更加愉快。

Python是一种强调简单性和可读性的语言,但在其干净的语法之下,隐藏着一个强大的、鲜为人知的特性的宝库。许多开发人员,即使是经验丰富的开发人员,也经常忽略其中的一些gem,这些gem可以帮助简化代码,提高效率,并使编程更加愉快。

在Python 3.8中引入的walrus运算符(:=)允许您将值作为表达式的一部分分配给变量。这对于减少循环和条件语句中的冗余非常有用。

没有海象操作符:

while len(text) > 5: print(f"'{text}' is too long!") text = input("Enter something: ")

使用walrus操作符:

while (text := input("Enter something: ")).strip and len(text) > 5: print(f"'{text}' is too long!")

第二个版本更简洁,不需要在循环外进行额外的变量赋值。

大多数程序员将elseif语句联系在一起,但在Python中,forwhile循环都可以有else子句。else下的块仅在循环完成而没有遇到break语句时才运行。

numbers = [1, 3, 5, 7]for num in numbers: if num % 2 == 0: print(f"Found an even number: {num}") breakelse: print("No even numbers found.")

在这里,else块仅在循环完成而没有命中break语句时执行。这在搜索列表中的项或运行验证检查时很有用。

Python的 * 运算符允许您以灵活的方式解包可迭代对象,使您能够提取特定部分,同时将其余部分收集到列表中。

first, *middle, last = [10, 20, 30, 40, 50]print(first) # 10print(middle) # [20, 30, 40]print(last) # 50

这在使用可变长度列表时特别有用,因为在这种情况下只需要特定的部分。

与编写长的if-elif链来确定调用哪个方法不同,可以使用getattr通过函数名动态调用函数。

class Greeter: def hello(self): return "Hello!" def goodbye(self): return "Goodbye!"g = Greeteraction = "hello" # This could be any user-defined stringprint(getattr(g, action)) # Calls g.hello

当处理基于用户输入、API响应或配置动态生成的方法调用时,这一点特别方便。

Python 3.9引入了一种更干净的方法来合并字典,|操作符.

dict1 = {“a”:1,“B”:2}dict2 = {“B”:3,“c”:4}Dict1| = dict2print(dict1)#{“a”:1,“b”:3,“c”:4}

这简化了字典更新,而无需使用.update或解包。

a , b = 5, 10a , b = b , aprint( a , b )#10,5

这是更有效的,并保持你的代码简洁。

collections模块中的defaultdict消除了在访问键之前检查键是否存在的需要。

defaultdict

word_count = {}words = ["apple", "banana", "apple", "orange"]for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1

使用defaultdict:

from collections import defaultdictword_count = defaultdict(int)for word in words: word_count[word] += 1

这简化了你的代码,使其更具可读性。

zip函数允许您同时循环多个可迭代对象,这使得它在处理成对数据时非常有用。

names = ["Alice", "Bob", "Charlie"]scores = [85, 90, 78]for name, score in zip(names, scores): print(f"{name}: {score}")

一旦最短的列表被耗尽,它就停止迭代,使其具有内存效率。

enumerate不是在循环中使用手动计数器,而是以一种干净的方式提供索引和值。

items = ["apple", "banana", "cherry"]for index, item in enumerate(items, start=1): print(f"{index}. {item}")

这消除了管理外部索引变量的需要。

map不需要编写显式的循环来转换数据,而是允许您将函数应用于可迭代对象中的所有元素。

numbers = [1, 2, 3, 4]squared = list(map(lambda x: x**2, numbers))print(squared) # [1, 4, 9, 16]

这对于简洁的数据转换很有用,而无需编写冗长的循环。

来源:自由坦荡的湖泊AI

相关推荐