2

I want to compare ListA[0] to ListB[0]...etc.

ListA = [itemA, itemB, itemC]
ListB = [true, false, true]

for item in ListA:
    if ListB[item] == True:
        print"I have this item"

Current problem is that [item] is not a number, so ListB[item] will not work. What is the correct way if I want to do something like this?

7 Answers 7

7

You can use itertools.compress:

Docstring:
compress(data, selectors) --> iterator over selected data

Return data elements corresponding to true selector elements.
Forms a shorter iterator from selected data elements using the
selectors to choose the data elements.

In [1]: from itertools import compress

In [2]: l1 = ['a','b','c','d']

In [3]: l2 = [True, False, True,False]

In [4]: for i in compress(l1,l2):
   ...:     print 'I have item: {0}'.format(i)
   ...:     
I have item: a
I have item: c
Sign up to request clarification or add additional context in comments.

Comments

7

You can iterate through the lists this way.

for a, b in zip(ListA, ListB):
    pass

Comments

1

You can use enumerate.

See this example:

http://codepad.org/sJ31ytWk

Comments

1

Try this:

for item, have_it in zip(ListA, ListB):
    if have_it:
        print "I have item", item

Comments

1

try this

for name,value in itertools.izip(ListA, ListB):
    if value == True:
        print "Its true"

Comments

1

Or you can do something like this:

[ a for a,b in zip(ListA,ListB) if b==True ]

Comments

1

If you want to compare each element of ListA with the corresponding element of ListB (in other words the elements at the same index numbers), you can use a for loop that iterates over the index numbers rather than iterating over the actual elements of one list. So your code would be: (note that range(len(ListA)-1) gives you a list of the numbers from 0 to the length of ListA, minus 1 since it's 0-indexing)

for i in range(len(ListA)-1):
      //ListA[i] will give you the i'th element of ListA
      //ListB[i] will give you the i'th element of ListB

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.