如何用for循环比较两个列表/数组?

2 投票
7 回答
7165 浏览
提问于 2025-04-17 14:10

我想把ListA的第一个元素和ListB的第一个元素进行比较,依此类推。

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

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

现在的问题是,[item]不是一个数字,所以用ListB[item]会出错。如果我想做到类似这样的事情,应该怎么做呢?

7 个回答

1

如果你想把列表ListA中的每个元素和列表ListB中对应位置的元素进行比较(也就是说,比较相同索引位置的元素),你可以使用一个for循环,循环遍历索引数字,而不是直接遍历某个列表中的元素。这样你的代码就可以写成: (注意,range(len(ListA)-1)会给你一个从0到ListA长度减1的数字列表,因为列表是从0开始计数的)

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
7

你可以这样遍历列表

for a, b in zip(ListA, ListB):
    pass
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

撰写回答