[英]how to find index of mismatch elements in two lists with two elements variants?
我有兩個不同的列表,其中包含兩個元素變體:“正”和“負”。 我做了一個列表理解來查找不匹配,但我無法使用 index() 返回索引,也許我在錯誤的地方使用了 function。 我正在努力做到這一點,以保持列表理解。
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]
i
和j
正在迭代列表的元素,而不是索引。 如果要獲取索引,使用python中的enumerate
function:
mismatch = [i for i, (a, b) in enumerate(zip(l1, l2)) if a != b]
這是使用range
而不是enumerate
和zip
的另一種方法:
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()
在列表長度不同的情況下會很有用。 過濾條件也可以寫得更清楚,如@JayMody's answer所示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.