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

标签 python list for-loop append conditional-statements

我有 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,而是 append 了整个列表 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]

关于Python循环遍历列表并根据条件追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31407792/

相关文章:

python - 对我来说最重要的问题 : is there a better way off doing it and if there is, 你们能给我指出正确的方向吗?

python - 使用 xlwt 将数组从特定列开始写入新工作簿

python - heapq.heapify 不适用于子类列表

python - wxPython 事件在启动时启动

reactjs - 更改列表项的背景

javascript - 使用for循环显示数组

javascript - For 循环中的 getElementById

javascript - 如何获得数字金字塔的正确 Javascript 输出

python - 变压器在管道中初始化两次

python - 如何正确使用倒计时线程,如何提前停止它?