查找两个数组之间的匹配索引的最佳方法

问题描述 投票:0回答:2

我对Python来说还很陌生,但是我试图在R中找到类似于%in%函数的函数/方法。我需要能够将列表的匹配项返回到列表的列表中。例如:

match = [1,2,3]
list = [[1,2,3], [1,5,2], [1,4], [15,1,8]]

function(match, list) 

理想情况下会返回0,但是[True False False False]也足够好。

python python-3.x
2个回答
0
投票

如果需要索引,可以这样操作:

indices = [i for i in range(len(list)) if list[i] == match]
print(indices)

结果:

[0]

注意:避免使用list作为变量名,因为它是Python中的保留关键字。


0
投票

您可以像这样使用列表理解:

[sublist == match for sublist in lst]

或者要获取第一个匹配子列表的索引,可以使用list.index方法:

lst.index(match)

请注意,如果在ValueError中找不到match,则上述方法将引发lst,因此应将其封装在try块中以正确处理异常:

try:
    index = lst.index(match)
except ValueError:
    print('match not found')
© www.soinside.com 2019 - 2024. All rights reserved.