walrus 运算符 (:=) 允许在表达式中赋值,从而减少冗余代码。
if (n := len(my_list)) > 5: print(f"List has {n} elements")这样可以避免两次调用 len(my_list),从而提高代码效率。
2. 使用functools.cache进行自动记忆Python 的 functools.cache 不是手动实现缓存,而是存储函数结果以便快速检索。
from functools import cache@cachedef factorial(n): return n * factorial(n - 1) if n else 1这通过避免冗余计算来加快重复函数调用的速度。
3. 用于格式化和调试的 F 字符串Python 的 f 字符串 (f“”) 现在支持 '='' 进行内联调试。
x, y = 10, 20print(f"x + y = {x + y}") # Output: x + y = 30它提供了一种更具可读性和更有效的方法来打印变量值。
4. 轻松合并词典Python 3.9+ 允许使用 | 和 |= 运算符进行字典合并。
d1 = {"a": 1, "b": 2}d2 = {"b": 3, "c": 4}d3 = d1 | d2 # {'a': 1, 'b': 3, 'c': 4}这简化了将词典合并到一行中的过程。
5. 使用zip()和strict=True进行更安全的迭代Python 3.10 在 zip() 中引入了 strict=True,如果输入可迭代对象的长度不同,则会引发错误。
list1 = [1, 2, 3]list2 = ['a', 'b']zipped = zip(list1, list2, strict=True) # Raises ValueError这可以防止由于长度不匹配而导致数据意外丢失。
6. 使用match语句进行干净的模式匹配Python 3.10 引入了结构模式匹配,它简化了复杂的条件逻辑。
def process_status(code): match code: case 200: return "OK" case 404: return "Not Found" case 500: return "Server Error" case _: return "Unknown Error"这为长 if-elif 链提供了一种优雅的替代方案。
7. 高效地逐行迭代文件与其一次读取所有文件,不如与 open() 和生成器一起使用以实现内存高效的读取。
with open("data.txt") as file: for line in file: print(line.strip())此方法处理大型文件,而不会消耗过多内存。
8. 使用itertools.groupby()对数据进行分组itertools.groupby() 通过根据关键函数对元素进行分组来简化数据聚合。
from itertools import groupbydata = [("A", 1), ("A", 2), ("B", 3), ("B", 4)]grouped = {k: list(v) for k, v in groupby(data, key=lambda x: x[0])}print(grouped) # {'A': [('A', 1), ('A', 2)], 'B': [('B', 3), ('B', 4)]}这对于有效地组织数据非常有用。
9. 使用contextlib.suppress()正常处理异常Python 的 contextlib.suppress() 不是使用 try-except-pass,而是使异常处理更简洁。
from contextlib import suppresswith suppress(FileNotFoundError): open("non_existent_file.txt")这可以防止不必要的错误处理代码使您的脚本混乱。
10. 使用if-else列出单行推导式列表推导式现在可以在单个可读行中包含 if-else 逻辑。
nums = [1, 2, 3, 4, 5]even_or_odd = ["Even" if x % 2 == 0 else "Odd" for x in nums]print(even_or_odd) # ['Odd', 'Even', 'Odd', 'Even', 'Odd']这使得列表转换更加高效和优雅。
