[英]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.