Python 实用技巧:10 个让代码更优雅的写法
前言
Python 以简洁著称,但很多初学者写出的代码却不够”Pythonic”。这篇文章分享 10 个实用技巧,让你的代码更优雅、更高效。
1. 用解构赋值交换变量
1 2 3 4 5 6 7
| temp = a a = b b = temp
a, b = b, a
|
2. 列表推导式代替 for 循环
1 2 3 4 5 6 7 8 9 10
| squares = [] for i in range(10): squares.append(i ** 2)
squares = [i ** 2 for i in range(10)]
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
|
3. 用 enumerate 代替手动计数
1 2 3 4 5 6 7 8 9
| index = 0 for item in items: print(index, item) index += 1
for index, item in enumerate(items): print(index, item)
|
4. 用 zip 同时遍历多个列表
1 2 3 4 5
| names = ["Alice", "Bob", "Charlie"] scores = [95, 87, 92]
for name, score in zip(names, scores): print(f"{name}: {score}")
|
5. 字典推导式
1 2 3 4
| names = ["alice", "bob", "charlie"] name_dict = {name: len(name) for name in names}
|
6. 用 get 安全访问字典
1 2 3 4 5
| value = my_dict["key"]
value = my_dict.get("key", "默认值")
|
7. 用 * 解包
1 2 3 4 5 6 7 8 9 10
| def add(a, b, c): return a + b + c
nums = [1, 2, 3] result = add(*nums)
first, *rest = [1, 2, 3, 4, 5]
|
8. f-string 格式化
1 2 3 4 5 6 7 8
| name = "Ren Echo" age = 22
print("我是%s,今年%d岁" % (name, age))
print(f"我是{name},今年{age}岁")
|
9. 用 with 管理文件
1 2 3 4 5 6 7 8
| f = open("data.txt", "r") content = f.read() f.close()
with open("data.txt", "r") as f: content = f.read()
|
10. 用 defaultdict 简化计数
1 2 3 4 5 6 7 8 9 10 11 12
| from collections import defaultdict
word_count = defaultdict(int) for word in words: word_count[word] += 1
from collections import defaultdict grouped = defaultdict(list) for item in items: grouped[item.category].append(item)
|
总结
| 技巧 |
适用场景 |
| 解构赋值 |
变量交换、函数返回多个值 |
| 列表推导式 |
简单的列表转换和过滤 |
| enumerate |
需要索引的遍历 |
| zip |
并行遍历多个序列 |
| get |
安全访问字典 |
| f-string |
字符串格式化 |
写 Python 的最高境界:能一行解决的事,绝不写两行(但也别过度压缩,可读性也很重要)。
你有什么 Python 技巧想分享吗?欢迎在评论区留言!