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

时间:2020-05-05 15:29:56

标签: python python-3.x list

因此我给了两个列表

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,有人可以在这里指出问题,谢谢

7 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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所说的是使用按位运算。

答案 1 :(得分:1)

假设它们的长度相同,则可以使用以下方法:

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

答案 2 :(得分:1)

关于如何做得更好的许多答案。

对于您的代码段,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

答案 3 :(得分:0)

您可以在一个循环中遍历值对及其索引:

for idx, (i, j) in enumerate(zip(lst1, lst2)):
    if i == j == 1:
        print(idx)

答案 4 :(得分:0)

您可以通过逐个元素and来做到这一点:

l = [i for i, _ in enumerate(lst1 and lst2) if _ == 1]

使用and函数,仅当两个列表的元素的值均为1时,表达式才返回1,这对于您的问题而言似乎是完美的。

答案 5 :(得分:0)

看,简单地遍历两个列表。假设您知道两个列表的长度,然后执行以下操作:

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

# as we know length of the both lists, and their length are equal, 
# i'll just write length as 5, but you can have other algorhitm of finding length

list_len = 5

is_there_any_matches = False

for index in range(list_len):

    if lst1[index] == lst2[index]:

       is_there_any_matches = True
       break                           # to exit after first match

请注意,这将在第一次比赛后中断循环,但是您可以删除break,然后计算比赛次数。另外,请始终采用较小列表的长度,以防止脚本因列表索引超出范围而出错。祝你玩得开心!


编辑

我试图使其尽可能简单,但是您可以使用生成器或其他pythonic技巧来使其更短,更方便地使用。

答案 6 :(得分:0)

您还可以使用NumPy的element-wise和操作,以及argwhere

>>> np.argwhere((np.array(lst1) == 1) & (np.array(lst2) == 1)).ravel()
array([2, 3])
相关问题