Python 列表推导式实用技巧

写出更简洁优雅的 Python 代码

Posted on 2024-12-18

列表推导式(List Comprehension)是 Python 中最优雅的特性之一。它让我们能用一行代码完成原本需要多行的循环操作。

基础语法

# 基本结构
[expression for item in iterable]

1. 创建数字列表

# 传统写法
squares = []
for i in range(10):
    squares.append(i ** 2)

# 列表推导式
squares = [i ** 2 for i in range(10)]
# 结果: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. 带条件的过滤

# 只保留偶数
evens = [x for x in range(20) if x % 2 == 0]
# 结果: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# 过滤字符串中的空字符
text = "hello world"
chars = [c for c in text if c != ' ']
# 结果: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

3. 处理字符串列表

# 统一转为大写
names = ['alice', 'bob', 'charlie']
upper_names = [name.upper() for name in names]
# 结果: ['ALICE', 'BOB', 'CHARLIE']

# 提取字符串长度
words = ['apple', 'banana', 'cherry']
lengths = [len(word) for word in words]
# 结果: [5, 6, 6]

4. 嵌套列表展平

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
# 结果: [1, 2, 3, 4, 5, 6, 7, 8, 9]

5. 带索引的转换

fruits = ['apple', 'banana', 'orange']
enumerated = [f'{i}: {fruit}' for i, fruit in enumerate(fruits)]
# 结果: ['0: apple', '1: banana', '2: orange']

6. 双重循环生成组合

colors = ['red', 'blue']
sizes = ['S', 'M', 'L']
combinations = [f'{color}-{size}' for color in colors for size in sizes]
# 结果: ['red-S', 'red-M', 'red-L', 'blue-S', 'blue-M', 'blue-L']

7. 条件表达式(三元运算符)

# 根据条件返回不同值
numbers = [1, 2, 3, 4, 5, 6]
labeled = ['even' if x % 2 == 0 else 'odd' for x in numbers]
# 结果: ['odd', 'even', 'odd', 'even', 'odd', 'even']

8. 字典转换为列表

scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
names = [name for name in scores.keys()]
values = [score for score in scores.values()]
# names: ['Alice', 'Bob', 'Charlie']
# values: [85, 92, 78]

何时避免使用

虽然列表推导式很简洁,但以下情况应该避免:

  • 逻辑过于复杂 - 超过两行条件判断时改用 for 循环
  • 需要异常处理 - 列表推导式不适合 try/except
  • 影响可读性 - 嵌套过深会让代码难以理解

总结

列表推导式让代码更简洁、更 Pythonic。合理使用能让代码质量提升一个档次,但也要注意不要过度使用而影响可读性。

Happy Coding!