我想将 ListA[0] 与 ListB[0]...等进行比较。
ListA = [itemA, itemB, itemC]
ListB = [true, false, true]
for item in ListA:
if ListB[item] == True:
print"I have this item"
当前的问题是 [item] 不是数字,因此 ListB[item] 将不起作用。如果我想做这样的事情,正确的方法是什么?
您可以通过这种方式遍历列表。
for a, b in zip(ListA, ListB):
pass
您可以使用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
尝试这个
for name,value in itertools.izip(ListA, ListB):
if value == True:
print "Its true"
尝试这个:
for item, have_it in zip(ListA, ListB):
if have_it:
print "I have item", item
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
或者你可以这样做:
[ a for a,b in zip(ListA,ListB) if b==True ]