2

我想将 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] 将不起作用。如果我想做这样的事情,正确的方法是什么?

4

7 回答 7

7

您可以通过这种方式遍历列表

for a, b in zip(ListA, ListB):
    pass
于 2013-01-30T08:13:52.057 回答
7

您可以使用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
于 2013-01-30T08:16:15.307 回答
1

尝试这个

for name,value in itertools.izip(ListA, ListB):
    if value == True:
        print "Its true"
于 2013-01-30T08:41:42.840 回答
1

您可以使用枚举。

看这个例子:

http://codepad.org/sJ31ytWk

于 2013-01-30T08:15:36.523 回答
1

尝试这个:

for item, have_it in zip(ListA, ListB):
    if have_it:
        print "I have item", item
于 2013-01-30T08:15:41.843 回答
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
于 2013-01-30T08:44:39.923 回答
1

或者你可以这样做:

[ a for a,b in zip(ListA,ListB) if b==True ]
于 2013-01-30T08:13:48.513 回答