【Python】Python中的列表推导式如何使用?

列表推导式(list comprehension)提供了一种快速构建列表的简洁方法。基本语法是:

## python www.itzhimei.com 代码
[expression for item in iterable]

这会遍历iterable中的每一项,计算expression的值,然后把结果作为元素添加到列表中。

示例:

## python www.itzhimei.com 代码
nums = [1, 2, 3, 4]
squares = [x**2 for x in nums] 
# [1, 4, 9, 16]

even_nums = [x for x in nums if x % 2 == 0]
# [2, 4] 

names = ['Bob', 'Alice', 'Bob', 'Alice']
names = [name.lower() for name in names]
# ['bob', 'alice', 'bob', 'alice']

列表推导式可以包含多个for循环来遍历嵌套的可迭代对象:

## python www.itzhimei.com 代码
matrix = [[1, 2], [3, 4]]
flat_list = [x for row in matrix for x in row]
# [1, 2, 3, 4]

列表推导式提供了一种精简的语法来创建列表,可以替代一行行的append操作。