编程就像讲故事:每一行都有其重要性,每一个细节都为整体画面添砖加瓦。然而,我们在 Python 提供的优雅快捷方式面前,常常被重复的任务或繁琐的语法所困扰,究竟有多少次我们会想,"一定有更好的方法"。
如果你曾有这样的想法,那么你来对地方了。
在这里,我将分享 15 个 Python 快捷键,能够显著提升你的编码速度,而不牺牲清晰度或准确性。
无论你是刚掌握列表推导的初学者,还是拥有多年经验的资深 Python 开发者(没错,我是在看着你),这里都有能让你更上一层楼的技巧。
快捷键:使用 contextlib.contextmanager
在一个函数中编写自定义上下文管理器。
与其编写冗长的 __enter__
和 __exit__
方法,不如用 contextlib.contextmanager
来轻松管理资源。
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!')
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!')
使用 |
运算符合并两个字典,而不是冗长的 .update()
方法或解包方式。
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3}
merged = {**dict1, **dict2}
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3}
merged = dict1 | dict2
你可能知道如何用 *args
解包列表,但你知道可以在任意参数位置进行解包吗?
def add(x, y, z):
return x + y + z
values = [1, 2, 3]
result = add(values[0], values[1], values[2])
def add(x, y, z):
return x + y + z
values = [1, 2, 3]
result = add(*values)
通过直接链式比较来省略冗余的逻辑运算符。
x = 5
if x > 3 and x < 10:
print("x is between 3 and 10")
x = 5
if 3 < x < 10:
print("x is between 3 and 10")
使用 @dataclass
省略手动定义 __init__
、__repr__
和相等性方法。
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)
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
在一个表达式中同时赋值和评估变量。
data = [1, 2, 3, 4]
n = len(data)
if n > 3:
print(f"List has {n} elements")
data = [1, 2, 3, 4]
if (n := len(data)) > 3:
print(f"List has {n} elements")
不再手动创建列表的反向副本,直接使用 reversed()
。
data = [1, 2, 3]
reversed_data = data[::-1]
for item in reversed_data:
print(item)
data = [1, 2, 3]
for item in reversed(data):
print(item)
通过自动缓存结果来加速递归函数。
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
from functools import cache
@cache
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
不再手动按换行符分割字符串,直接使用 splitlines()
。
text = "Line1\nLine2\nLine3"
lines = text.split('\n')
text = "Line1\nLine2\nLine3"
lines = text.splitlines()
在循环中放弃手动计数器 - 使用 enumerate()
进行干净可读的解决方案。
items = ['a', 'b', 'c']
index = 0
for item in items:
print(index, item)
index += 1
items = ['a', 'b', 'c']
for index, item in enumerate(items):
print(index, item)
使用推导在一行中创建字典。
data = [1, 2, 3]
squares = {}
for x in data:
squares[x] = x ** 2
data = [1, 2, 3]
squares = {x: x ** 2 for x in data}
在多个序列上并行迭代,无需手动索引。
names = ['Alice', 'Bob']
ages = [25, 30]
for i in range(len(names)):
print(f"{names[i]} is {ages[i]} years old")
names = ['Alice', 'Bob']
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
轻松将嵌套列表简化为单一序列。
nested = [[1, 2], [3, 4]]
flattened = []
for sublist in nested:
for item in sublist:
flattened.append(item)
from itertools import chain
nested = [[1, 2], [3, 4]]
flattened = list(chain.from_iterable(nested))
提前固定某些函数参数,以便更干净地重用。
def power(base, exp):
return base ** exp
def square(x):
return power(x, 2)
from functools import partial
power = lambda base, exp: base ** exp
square = partial(power, exp=2)
使用 os.path.join
进行平台无关的文件路径处理。
path = "folder" + "/" + "file.txt"
import os
path = os.path.join("folder", "file.txt")