Python列表推导式
1. 基本语法
列表推导式的核心语法如下:
[expression for item in iterable]expression: 计算结果将被添加到新列表中的表达式。它可以是对item的操作,或者仅仅是item本身。item: 代表iterable中当前遍历到的元素。iterable: 任何可以被遍历的对象(例如列表、字符串、range 对象等)。
示例:创建一个包含 0 到 9 平方的列表
- 传统方法 (使用
for循环):
squares = []
for x in range(10):
squares.append(x**2)
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]- 使用列表推导式:
squares = [x**2 for x in range(10)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]2. 添加条件判断 (过滤)
你可以在列表推导式中添加 if 语句,以过滤掉不满足条件的元素。
[expression for item in iterable if condition]condition: 一个布尔表达式。只有当condition为True时,对应的expression结果才会被添加到新列表中。
示例:获取 0 到 19 之间的所有偶数
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # 输出: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]示例:过滤出长度大于 3 的单词,并转换为大写
words = ["apple", "bat", "cat", "banana", "dog"]
long_words = [word.upper() for word in words if len(word) > 3]
print(long_words) # 输出: ['APPLE', 'BANANA']3. 使用 if-else 结构
当你想根据条件改变 expression 的结果,而不是过滤掉元素时,你需要将 if-else 结构放在 for 循环之前。
[expression_if_true if condition else expression_if_false for item in iterable]示例:将列表中的正数保持不变,将负数替换为 0
numbers = [1, -5, 3, -2, 8]
processed_numbers = [x if x > 0 else 0 for x in numbers]
print(processed_numbers) # 输出: [1, 0, 3, 0, 8]4. 嵌套循环
列表推导式也支持多个 for 循环,这就相当于嵌套的 for 循环。
[expression for item1 in iterable1 for item2 in iterable2]示例:生成两个列表元素的笛卡尔积
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
combinations = [(color, size) for color in colors for size in sizes]
print(combinations)
# 输出: [('red', 'S'), ('red', 'M'), ('red', 'L'), ('blue', 'S'), ('blue', 'M'), ('blue', 'L')]等效的传统代码:
combinations = []
for color in colors:
for size in sizes:
combinations.append((color, size))5. 多维列表的展平
可以使用嵌套的列表推导式将一个二维列表(或多维)展平为一个一维列表。
示例:展平一个二维矩阵
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
flattened = [num for row in matrix for num in row]
print(flattened) # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]
评论 (0)