1

I have 3 very lengthy lists (of length 15,000). Lets say for example the three lists are:

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

I would like to get all those values of B and C that are where the corresponding index of A is 0. For example if A[i] == 0 then I would like to add B[i] to listB_0 and C[i] to listC_0.

I tried

listB_0 = []
listC_0 = []

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

But this seems to put Python through a never ending loop, even after 5 minutes, I see that the program is still running.

What I finally want is, for example the listB and listC for which listA = 0 will be

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

What is the correct way to achieve this?

3
  • 3
    It looks like you are appending the entire list B instead of the element b. Commented Jul 14, 2015 at 13:21
  • that was my guess as well!! How do I append according to the above condition? Commented Jul 14, 2015 at 13:21
  • 4
    listB_0.append(b) and listC_0.append(c) Commented Jul 14, 2015 at 13:22

4 Answers 4

2

As noted in comments, you should append b instead of B. I want to note, that you can use list comprehension instead of loop to get results "pythonic" way.

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]
Sign up to request clarification or add additional context in comments.

Comments

1

Brobin already pointed this out in his comment: Instead of b or c, the whole lists B or C get appended.

This should work:

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]

Comments

1

You want to append the values b for listB_0 and c for listC_0, not the lists themselves.

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

Comments

1

There is really no need for zip() here:

# 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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.