列表生成式

Python列表生成式(List Comprehensions)教程

1. 基本概念

列表生成式(List Comprehensions)是Python中一种简洁而强大的创建列表的方式。它可以用一行代码替代传统的循环语句来生成列表,使代码更加简洁易读。

2. 基本语法

[expression for item in iterable]

2.1 简单示例

# 生成1-10的平方列表
squares = [x**2 for x in range(1, 11)]
print(squares)  # 输出: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3. 带条件的列表生成式

3.1 过滤条件

# 只包含偶数的平方
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares)  # 输出: [4, 16, 36, 64, 100]

3.2 条件表达式

# 如果是偶数则保留原值,否则取负值
numbers = [x if x % 2 == 0 else -x for x in range(1, 11)]
print(numbers)  # 输出: [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]

注意iffor之后是过滤条件,不能带else;而在for之前是条件表达式,必须完整(带else)。

4. 多层循环

4.1 双重循环

# 生成全排列组合
combinations = [m + n for m in 'ABC' for n in 'XYZ']
print(combinations)  # 输出: ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

4.2 三重循环(不常用)

# 生成三维坐标点
points = [(x, y, z) for x in range(2) for y in range(2) for z in range(2)]
print(points)  # 输出: [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

5. 实际应用示例

5.1 处理字典

# 字典键值对格式化
d = {'x': 'A', 'y': 'B', 'z': 'C'}
formatted = [f"{k}={v}" for k, v in d.items()]
print(formatted)  # 输出: ['x=A', 'y=B', 'z=C']

5.2 文件系统操作

import os

# 列出当前目录下所有文件和目录
files_and_dirs = [d for d in os.listdir('.')]
print(files_and_dirs)

5.3 字符串处理

# 将列表中的字符串转为小写
words = ['Hello', 'World', 'IBM', 'Apple']
lower_words = [word.lower() for word in words]
print(lower_words)  # 输出: ['hello', 'world', 'ibm', 'apple']

6. 类型安全处理

当列表中混合不同类型时,可以使用isinstance()进行类型检查:

mixed = ['Hello', 'World', 18, 'Apple', None]
safe_lower = [s.lower() for s in mixed if isinstance(s, str)]
print(safe_lower)  # 输出: ['hello', 'world', 'apple']

7. 练习题

L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s, str)]

# 测试
print(L2)
if L2 == ['hello', 'world', 'apple']:
    print('测试通过!')
else:
    print('测试失败!')

8. 性能考虑

列表生成式通常比等效的for循环更快,因为:

  1. 解释器可以优化列表生成式的执行
  2. 减少了Python字节码的执行次数

但在处理大数据量时,考虑使用生成器表达式(将[]换成())以节省内存。

9. 现代Python中的扩展

Python 3.8+引入了海象运算符(:=),可以在列表生成式中使用:

# 计算平方并保留大于50的值
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = [square for x in numbers if (square := x**2) > 50]
print(result)  # 输出: [64, 81, 100]

10. 总结

列表生成式是Python中非常实用的特性,能够:

  • 使代码更简洁
  • 提高可读性(当使用恰当时)
  • 通常有更好的性能

建议在简单转换和过滤场景中使用列表生成式,复杂逻辑仍使用传统循环以提高可读性。