[英]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. I'm pretty new to Python, but I am trying to find a function / method similar to the %in% function in R. I need to be able to return the matches of a list, to a list of lists.
我需要能够将列表的匹配项返回到列表列表。 For example:
例如:
match = [1,2,3]
list = [[1,2,3], [1,5,2], [1,4], [15,1,8]]
function(match, list)
Which would return 0
, ideally, but [True False False False]
is good enough too.理想情况下,这将返回
0
,但[True False False False]
也足够好。
You can use a list comprehension like this:您可以使用这样的列表推导:
[sublist == match for sublist in lst]
Or to obtain the index of the first matching sub-list, you can use the list.index
method:或者要获取第一个匹配的子列表的索引,可以使用
list.index
方法:
lst.index(match)
Note that the above method would raise a ValueError
if match
is not found in lst
, so you should enclose it in a try
block to handle the exception properly:请注意,如果在
lst
中找不到match
项,上述方法将引发ValueError
,因此您应该将其包含在try
块中以正确处理异常:
try:
index = lst.index(match)
except ValueError:
print('match not found')
If you want the indices, you can do it like this:如果你想要索引,你可以这样做:
indices = [i for i in range(len(list)) if list[i] == match]
print(indices)
Result:结果:
[0]
Note : Avoid using list
as a variable name, as it is a reserved keyword in Python.注意:避免使用
list
作为变量名,因为它是 Python 中的保留关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.