我有一个由给定数量的子列表组成的列表。我需要根据存储在第一个中的值拒绝所有子列表中的项目来创建一个新的(较小的)列表。 这就是我所说的MWE:
a = [[0,0,0,1,1,1,2,2,2], [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9],
[0.21,0.22,0.23,0.24,0.25,0.26,0.27,0.28,0.29]]
b = [[] for _ in range(len(a))]
for indx, item in enumerate(a[0]):
if item == 2:
b[0].append(a[0][indx])
b[1].append(a[1][indx])
b[2].append(a[2][indx])
导致:
[[2, 2, 2], [0.7, 0.8, 0.9], [0.27, 0.28, 0.29]]
这很有效,但我正在寻找一种更加pythonic的方式来创建我的b
列表。
答案 0 :(得分:4)
使用zip()
将列表合并到列中,过滤列,然后再次使用zip()
转置回行:
b = zip(*(col for col in zip(*a) if col[0] == 2))
演示:
>>> a = [[0,0,0,1,1,1,2,2,2], [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9],
... [0.21,0.22,0.23,0.24,0.25,0.26,0.27,0.28,0.29]]
>>> zip(*(col for col in zip(*a) if col[0] == 2))
[(2, 2, 2), (0.7, 0.8, 0.9), (0.27, 0.28, 0.29)]
这会创建一个元组列表。如果您绝对需要列表,请映射到列表:
b = map(list, zip(*(col for col in zip(*a) if col[0] == 2)))
或者,在Python 3中,使用列表推导:
b = [list(t) for t in zip(*(col for col in zip(*a) if col[0] == 2))]