整理几个经常用到、但容易记混的写法,示例都可以直接跑。
切片的妙用
nums = [1, 2, 3, 4, 5]
nums[:3] # [1, 2, 3] 前三个
nums[-2:] # [4, 5] 后两个
nums[::2] # [1, 3, 5] 隔一个取一个
s = "hello"
s[::-1] # "olleh" 字符串反转
推导式
squares = [x * x for x in range(10)]
evens = [x for x in nums if x % 2 == 0]
lengths = {w: len(w) for w in ["git", "python", "linux"]}
zip 与解包
names = ["a", "b", "c"]
scores = [90, 85, 88]
pairs = list(zip(names, scores)) # [('a', 90), ('b', 85), ...]
first, *rest = [1, 2, 3, 4] # first=1, rest=[2, 3, 4]
字典取值的安全写法
cfg = {"host": "127.0.0.1"}
cfg.get("port", 8080) # 不存在时返回默认值 8080,而不是 KeyError
原则:推导式超过一行就读不清时,就老老实实写 for 循环。简洁是手段,可读才是目的。