Python 知识点： 列表推导式(list comprehension)

0
1
0
1. 云栖社区>
2. 博客>
3. 正文

## Python 知识点： 列表推导式(list comprehension)

xiaoyuaner 2019-03-15 16:47:31 浏览518

Python里面有个很棒的语法糖（syntactic sugar），它就是 list comprehension ，有人把它翻译成“列表推导式”，也有人翻译成“列表解析式”。名字听上去很难理解，但是看它的语法就很清晰了。虽然名字叫做 list comprehension，但是这个语法同样适用于dict、set等这一系列可迭代（iterable）数据结构。

out_list = [out_express for out_express in input_list if out_express_condition]

In [1]: evens = [i for i in range(10) if i % 2 == 0]
In [2]: evens
Out[2]: [0, 2, 4, 6, 8]


evens = []
for i in range(10):
if i % 2 == 0:
evens.append(i)


squares = [i**2 for i in range(10)]


matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]

flattened = []

for row in matrix:
for i in row:
flattened.append(i)


flattened = [i for row in matrix for i in row]


evens = [i for i in range(10) if i % 2 == 0]


evens = [
i
for i in range(10)
if i % 2 == 0
]


flattened = [i for row in matrix for i in row]

flattened = [
i
for row in matrix
for i in row
]


changed = {value: key for key, value in input_dict.items()}



chars = {w[0] for w in words_list}


xiaoyuaner
+ 关注