【问题标题】:Python loop through lists and append according to conditionsPython循环遍历列表并根据条件追加
【发布时间】:2015-10-03 03:49:07
【问题描述】:

我有 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

我想获取所有那些 A 的对应索引为 0 的 B 和 C 值。例如,如果 A[i] == 0 那么我想将 B[i] 添加到 listB_0 和 C[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] 

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

【问题讨论】:

  • 看起来您正在附加整个列表 B 而不是元素 b。
  • 这也是我的猜测!!如何根据上述条件追加?
  • listB_0.append(b) 和 listC_0.append(c)

标签: python list for-loop append conditional-statements


【解决方案1】:

Brobin 已经在他的评论中指出了这一点:不是b 或c,而是整个列表B 或C 被附加。

这应该可行:

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]

【讨论】:

    【解决方案2】:

    您想为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)
    

    【讨论】:

      【解决方案3】:

      如 cmets 中所述,您应该附加 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]
      

      【讨论】:

        【解决方案4】:

        这里真的不需要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])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-24
          • 1970-01-01
          • 2017-03-24
          • 2018-10-26
          • 2019-04-15
          • 1970-01-01
          相关资源
          最近更新 更多