如何在具有两个元素变体的两个列表中找到不匹配元素的索引?

how to find index of mismatch elements in two lists with two elements variants?

我有两个不同的列表,其中包含两个元素变体:'POSITIVE' 和 'NEGATIVE'。我做了一个列表理解来找到不匹配的地方,但我不能 return 使用 index() 的索引,也许我在错误的地方使用了这个函数。我正在努力做到这一点,以保持对列表的理解。

代码

l1 = ['POSITIVE', 'NEGATIVE', 'POSITIVE', 'NEGATIVE', 'POSITIVE', 'NEGATIVE',
           'POSITIVE', 
           'POSITIVE', # mismatch
           'POSITIVE', 
           'POSITIVE'] # mismatch

l2 = ['POSITIVE', 'NEGATIVE', 'POSITIVE', 'NEGATIVE', 'POSITIVE', 'NEGATIVE',
           'POSITIVE', 
           'NEGATIVE', # mismatch
           'POSITIVE', 
           'NEGATIVE'] # mismatch

mismatch = [i for i, j in zip(l1, l2) if i != j]

print(mismatch)
['POSITIVE', 'POSITIVE']

# expected output
[7, 9]

ij 迭代列表的元素,而不是索引。如果要获取索引,使用python中的enumerate函数:

mismatch = [i for i, (a, b) in enumerate(zip(l1, l2)) if a != b]

这是使用 range 代替 enumeratezip 的另一种方法:

mismatch = [i for i in range(len(l1)) if l1[i] != l2[i]]

关键是当您想同时迭代值和索引时使用 enumerate()。你真的不需要 zip():

mismatch = [i for i,v in enumerate(l1) if v != l2[i]]

尽管 zip() 在列表长度不同的情况下会有所帮助。另外过滤条件可以写的更清楚如.