gpt4 book ai didi

python - 如何使用for循环将2个列表/数组与python进行比较?

转载 作者:行者123 更新时间:2023-11-28 19:32:08 25 4
gpt4 key购买 nike

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

最佳答案

您可以使用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

关于python - 如何使用for循环将2个列表/数组与python进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14599307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com