1

我有一个由给定数量的子列表组成的列表。我需要根据存储在第一个列表中的值拒绝所有子列表中的项目来创建一个新的(较小的)列表。这就是我的意思的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列表。

4

1 回答 1

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))]
于 2013-10-31T14:05:19.047 回答