Featured image of post Python的List Comprehension(列表推导式)

Python的List Comprehension(列表推导式)

如何更高效的创建列表

Python提供了一个高效的列表推导式(List Comprehension)

语法如下

1
2
3
4

values = [expression
        for value in collection
        if condition]

等价于

1
2
3
4
5

vals = []
for value in collection:
	if condition:
		vals.append(expression)

举个简单的例子

1
2
3

even_squares = [x * x for x in range(10) if not x % 2]
print(even_squares)

输出结果如下

1
2

[0, 4, 16, 36, 64]

列表推导式(List Comprehension)还有更多好用的方法,后面继续补充

Licensed under CC BY-NC-SA 4.0
最后更新于 Jul 30, 2025 09:57 +0800