15 个高级 Python 快捷方式,加快编码速度
编码就像讲故事:每行都很重要,每个细节都有助于整体的发展。然而,当 Python 为我们提供了优雅的快捷方式时,我们是否经常发现自己陷入重复的任务或笨拙的语法中?
在这里,我将分享 15 个 Python 快捷方式,它们将在不牺牲清晰度或准确性的情况下提高的编码速度。
无论是仍在掌握列表推导的初学者,还是拥有多年经验的经验丰富的 Pythonista(是的,我正在看着),这里都有一些内容可以帮助提高技能。
1. 无处不在的上下文管理器
快捷方式:用于contextlib.contextmanager在单个函数中编写自定义上下文管理器。
无需编写笨重__enter__的__exit__方法,使用contextlib.contextmanager轻量级的资源管理。
Without it:
class FileManager:
def __init__(self, filename):
self.filename = filename def __enter__(self):
self.file = open(self.filename, 'w')
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
with FileManager('example.txt') as f:
f.write('Hello, World!')
With it:
from contextlib import contextmanager@contextmanager
def file_manager(filename):
file = open(filename, 'w')
try:
yield file
finally:
file.close()
with file_manager('example.txt') as f:
f.write('Hello, World!')
2. 内联字典合并(Python 3.9+)
使用|运算符来合并两个字典,而不是使用详细.update()方法或解包。
Without it:
dict1 = { 'a' : 1 , 'b' : 2 }
dict2 = { 'c' : 3 }
merged = {**dict1, **dict2}
With it:
dict1 = { 'a' : 1 , 'b' : 2 }
dict2 = { 'c' : 3 }
merged = dict1 | dict2
3.用*函数参数解包
可能知道如何使用 来解包列表*args,但是是否知道可以将解包用于任意参数位置?
Without it:
def add(x, y, z):
return x + y + zvalues = [1, 2, 3]
result = add(values[0], values[1], values[2])
With it:
def add(x, y, z):
return x + y + zvalues = [1, 2, 3]
result = add(*values)
4. 链式比较
通过直接链接比较来跳过冗余的逻辑运算符。
Without it:
x = 5
if x > 3 and x < 10:
print("x is between 3 and 10")
With it:
x = 5
if 3 < x < 10:
print("x is between 3 and 10")
5.dataclasses用于轻量级类
跳过手动使用__init__、__repr__和等号方法定义@dataclass。
Without it:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y def __repr__(self):
return f"Point({self.x}, {self.y})"
p = Point(1, 2)
With it:
from dataclasses import dataclass@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
6. 海象运算符(:=)
在单个表达式中分配和评估变量。
Without it:
data = [1, 2, 3, 4]
n = len(data)
if n > 3:
print(f"List has {n} elements")
With it:
data = [1, 2, 3, 4]
if (n := len(data)) > 3:
print(f"List has {n} elements")
7. 轻松逆转reversed()
无需手动创建列表的反向副本。reversed()直接使用。
Without it:
data = [1, 2, 3]
reversed_data = data[::-1]
for item in reversed_data:
print(item)
With it:
data = [1, 2, 3]
for item in reversed(data):
print(item)
8.functools.cache用于记忆
通过自动缓存结果来加速递归函数。
Without it:
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
With it:
from functools import cache@cache
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
9. splitlines()快速将字符串转换为列表
不要手动在换行符处拆分字符串,而是使用splitlines()。
Without it:
text = "Line1\nLine2\nLine3"
lines = text.split('\n')
With it:
text = "Line1\nLine2\nLine3"
lines = text.splitlines()
10.enumerate()用于清洁索引跟踪
抛弃循环中的手动计数器——使用enumerate()干净、可读的解决方案。
Without it:
items = ['a', 'b', 'c']
index = 0
for item in items:
print(index, item)
index += 1
With it:
items = ['a', 'b', 'c']
for index, item in enumerate(items):
print(index, item)
11. 字典推导式
使用理解在一行中创建字典。
Without it:
data = [1, 2, 3]
squares = {}
for x in data:
squares[x] = x ** 2
With it:
data = [1, 2, 3]
squares = {x: x ** 2 for x in data}
12.zip()并行迭代
并行迭代多个序列,无需手动索引。
Without it:
names = ['Alice', 'Bob']
ages = [25, 30]
for i in range(len(names)):
print(f"{names[i]} is {ages[i]} years old")
With it:
names = ['Alice', 'Bob']
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
13.itertools.chain扁平嵌套列表
轻松将嵌套列表简化为单个序列。
Without it:
nested = [[1, 2], [3, 4]]
flattened = []
for sublist in nested:
for item in sublist:
flattened.append(item)
With it:
from itertools import chain
nested = [[1, 2], [3, 4]]
flattened = list(chain.from_iterable(nested))
14.functools.partial部分函数
提前修复函数的某些参数以便更干净地重用。
Without it:
def power(base, exp):
return base ** expdef square(x):
return power(x, 2)
With it:
from functools import partial
power = lambda base, exp: base ** exp
square = partial(power, exp=2)
15.os.path安全文件路径
用于os.path.join独立于平台的文件路径处理。
Without it:
path = "folder" + "/" + "file.txt"
With it:
import os
path = os.path.join("folder", "file.txt")
🏴☠️宝藏级🏴☠️ 原创公众号『数据STUDIO』内容超级硬核。公众号以Python为核心语言,垂直于数据科学领域,包括可戳👉Python|MySQL|数据分析|数据可视化|机器学习与数据挖掘|爬虫 等,从入门到进阶!
长按👇关注- 数据STUDIO -设为星标,干货速递