繁体   English   中英

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

[英]Best way to find the index of a match between two arrays

I'm pretty new to Python, but I am trying to find a function / method similar to the %in% function in R. 我需要能够将列表的匹配项返回到列表列表。 例如:

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

function(match, list) 

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

您可以使用这样的列表推导:

[sublist == match for sublist in lst]

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

lst.index(match)

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

try:
    index = lst.index(match)
except ValueError:
    print('match not found')

如果你想要索引,你可以这样做:

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

结果:

[0]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM