我对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]
也足够好。
如果需要索引,可以这样操作:
indices = [i for i in range(len(list)) if list[i] == match]
print(indices)
结果:
[0]
注意:避免使用list
作为变量名,因为它是Python中的保留关键字。
您可以像这样使用列表理解:
[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')