Python 中没人告诉你的10个酷炫功能
Python 是一种强调简洁和可读性的语言,但其干净的语法之下隐藏着丰富的强大且不太为人所知的特性。许多开发者,即使是经验丰富的开发者,也常常忽视这些宝石,它们可以帮助简化代码、提高效率,并使编程更加愉快。在本文中,我们将探讨一些许多人没有谈论但可以改变你编写代码方式的有趣 Python 特性。
1 海象操作符(:=)— 一举赋值和使用
Python 3.8 中引入的 walrus 操作符 (:=) 允许您在表达式中将值赋给变量。这可以大大减少循环和条件语句中的冗余。
没有海象操作符:
text = input("Enter something: ")
while len(text) > 5:
print(f"'{text}' is too long!")
text = input("Enter something: ")
使用海象操作符:
while (text := input("Enter something: ")).strip() and len(text) > 5:
print(f"'{text}' is too long!")
第二个版本更简洁,无需在循环外部进行额外的变量赋值。
2. 循环中的 else 子句——它并非你所想
大多数程序员将else与if语句相关联,但在 Python 中,for和while循环都可以有一个else子句。在else下的代码块仅在循环在遇到break语句之前完成时才运行。
示例:
numbers = [1, 3, 5, 7]
for num in numbers:
if num % 2 == 0:
print(f"Found an even number: {num}")
break
else:
print("No even numbers found.")
这里,else 块仅在循环未遇到break语句时执行。这在搜索列表中的项目或运行验证检查时很有用。
3. 扩展可迭代解包 — 捕获列表的一部分
Python 的 * 运算符允许您以灵活的方式解包可迭代对象,使您能够提取特定部分,同时将剩余部分收集到一个列表中。
first, *middle, last = [10, 20, 30, 40, 50]
print(first) # 10
print(middle) # [20, 30, 40]
print(last) # 50
这对于处理需要仅特定部分的变长列表尤其有用。
4. 使用 getattr()进行动态方法调用
代替编写长的if-elif链来确定调用哪个方法,您可以使用getattr()通过名称动态调用一个函数。
class Greeter:
def hello(self):
return "Hello!"
def goodbye(self):
return "Goodbye!"
g = Greeter()
action = "hello" # This could be any user-defined string
print(getattr(g, action)()) # Calls g.hello()
这特别方便处理基于用户输入、API 响应或配置动态生成的调用方法。
5. 字典合并使用 |= 操作符
Python 3.9 引入了使用|运算符合并字典的更简洁方法。
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1 |= dict2
print(dict1) # {'a': 1, 'b': 3, 'c': 4}
这简化了字典更新,无需使用.update()或解包。
6. 无临时变量的内联交换
在大多数语言中,交换两个变量需要临时变量,但 Python 允许单行交换:
a, b = 5, 10
a, b = b, a
print(a, b) # 10, 5
这是更高效且使您的代码更简洁。
7. defaultdict 的力量
从 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 defaultdict
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
这简化了您的代码,并使其更易于阅读。
8. 使用 zip()遍历多个列表
The zip() 函数允许您同时遍历多个可迭代对象,这在处理成对数据时非常有用。
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
它停止迭代,一旦最短列表耗尽,使其内存效率高。
9. 枚举()函数 —— 不再需要手动索引
代替在循环中使用手动计数器,enumerate() 以一种干净的方式同时提供索引和值。
items = ["apple", "banana", "cherry"]
for index, item in enumerate(items, start=1):
print(f"{index}. {item}")
这消除了管理外部索引变量的需求。
10. map() 函数用于更简洁的转换
代替编写显式的循环来转换数据,map() 允许您将一个函数应用于可迭代对象中的所有元素。
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16]
这对于简洁的数据转换非常有用,无需编写冗长的循环。