Python检查两个列表在同一索引中是否具有相同的值

2024-04-19 12:49:08 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我给了两张清单

lst1 =[0,1,1,1,0]
lst2 =[0,0,1,1,0]

我需要看看两个列表中哪个索引的值都是1,这是我目前的代码

x = list(zip(lst1,lst2))
for i in range(len(x)):
    flag = 0
    for y in range(len(x[i])):
        if x[i][y] == 1:
            flag +=1
    if flag == 2:
        z = x.index(x[i])
        print(z)

但是这打印的是索引2和2,而不是2和3。有人能指出这里的问题吗,谢谢


Tags: 代码in列表forindexlenifrange
3条回答

关于如何做得更好,有很多答案

对于您的代码段,List.index始终给出列表中的第一个匹配元素。这就是我们2,2的原因

>>> lst1 =[0,1,1,1,0]
>>> lst2 =[0,0,1,1,0]
>>> x = list(zip(lst1,lst2))
>>> x
[(0, 0), (1, 0), (1, 1), (1, 1), (0, 0)]
>>> x.index((1,1))
2
>>> x.index((1,1))
2

假设它们的长度相同,您可以使用:

>>> [i for i, (x, y) in enumerate(zip(lst1, lst2)) if x == y == 1]
[2, 3]

您可以执行以下操作:

lst1 =[0,1,1,1,0]
lst2 =[0,0,1,1,0]
assert len(lst1) == len(lst2)

idx = [i for i in range(len(lst1)) if lst1[i] == 1 and lst2[i] == 1]

print(idx)

使用numpy的其他解决方案是:

import numpy as np

lst1 =[0,1,1,1,0]
lst2 =[0,0,1,1,0]
assert len(lst1) == len(lst2)
lst1_ = np.array(lst1)
lst2_ = np.array(lst2)

idx_ = np.intersect1d(np.where(lst1_ == 1)[0],np.where(lst2_ == 1)[0])
print(list(idx_))

另一种选择是切换以下线路:

idx_ = np.intersect1d(np.where(lst1_ == 1)[0],np.where(lst2_ == 1)[0])

作者:

idx_ = np.where((lst1_==1)&(lst2_==1))[0]

如@yatu所述,它使用位运算

相关问题 更多 >