Python 实用技巧:10 个让代码更优雅的写法

Python 实用技巧:10 个让代码更优雅的写法

Ren Echo Lv4

前言

Python 以简洁著称,但很多初学者写出的代码却不够”Pythonic”。这篇文章分享 10 个实用技巧,让你的代码更优雅、更高效。

1. 用解构赋值交换变量

1
2
3
4
5
6
7
# ❌ 传统写法
temp = a
a = b
b = temp

# ✅ Pythonic 写法
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

# ✅ enumerate
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}
# {'alice': 5, 'bob': 3, 'charlie': 7}

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) # 等同于 add(1, 2, 3)

# 列表解包
first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [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))

# ✅ f-string(推荐)
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 技巧想分享吗?欢迎在评论区留言!

  • 标题: Python 实用技巧:10 个让代码更优雅的写法
  • 作者: Ren Echo
  • 创建于 : 2026-05-28 15:00:00
  • 更新于 : 2026-06-27 10:06:11
  • 链接: https://renecho-blog.pages.dev/2026/05/28/python-tips/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论