简体   繁体   中英

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 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.

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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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