Python 遍历列表并根据条件追加

Python loop through lists and append according to conditions

我有 3 个非常长的列表(长度为 15,000)。比方说这三个列表是:

A    B    C
0    2    3
0    4    5
0    3    3
1    2    6
1    3    5
0    2    7
1    8    8

我想获取 B 和 C 的所有那些值,这些值是 A 的相应索引为 0 的地方。例如,如果 A[i] == 0 那么我想将 B[i] 添加到 listB_0C[i]listC_0

我试过了

listB_0 = []
listC_0 = []

for a,b,c in zip(A,B,C):
    if a == 0:
        listB_0.append(B)
        listC_0.append(C)

但这似乎让 Python 进入了一个永无止境的循环,甚至在 5 分钟后,我看到程序仍然是 运行。

我最终想要的是,例如 listA = 0 的 listB 和 listC

listB_0 = [2,4,3,2]
listC_0 = [3,5,3,7] 

实现此目标的正确方法是什么?

Brobin 已经在他的评论中指出了这一点:不是 bc,而是附加了整个列表 BC

这应该有效:

A = [0, 0, 0, 1, 1, 0, 1]
B = [2, 4, 3, 2, 3, 2, 8]
C = [3, 5, 3, 6, 5, 7, 8]

listB_0 = []
listC_0 = []

for a, b, c in zip(A,B,C):
    if a == 0:
        listB_0.append(b)
        listC_0.append(c)

print listB_0
print listC_0

>>> 
[2, 4, 3, 2]
[3, 5, 3, 7]

您想为 listB_0 附加值 b 和为 listC_0 附加值 c,而不是列表本身。

for a,b,c in zip(A,B,C):
    if a == 0:
        listB_0.append(b)
        listC_0.append(c)

如评论中所述,您应该附加 b 而不是 B。我想指出,您可以使用列表理解而不是循环来获得结果 "pythonic" 方式。

A = [0, 0, 0, 1, 1, 0, 1]
B = [2, 4, 3, 2, 3, 2, 8]

listB_0 = [b for a, b in zip(A, B) if a == 0]
print(listB_0)  # [2, 4, 3, 2]

这里真的不需要zip():

# use xrange(len(A)) if in Python 2
for i in range(len(A)):
    if A[i] == 0:
        listB_0.append(B[i])
        listC_0.append(C[i])