python3 list comprehensions

1,表达式定义为

在这里插入图片描述
例子:

a_list = [1, ‘4’, 9, ‘a’, 0, 4]

squared_ints = [ e**2 for e in a_list if type(e) == types.IntType ]

print squared_ints
# [ 1, 81, 0, 16 ]

2,构造矩阵

[ [ 1 if item_idx == row_idx else 0 for item_idx in range(0, 3) ] for row_idx in range(0, 3) ]
#output
#[[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Reference

https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Comprehensions.html

猜你喜欢

转载自blog.csdn.net/linkequa/article/details/88419562