use*_*516 12 python list match indices
对于两个列表a和b,我如何获得两者中出现的值的索引?例如,
a = [1, 2, 3, 4, 5]
b = [9, 7, 6, 5, 1, 0]
return_indices_of_a(a, b)
Run Code Online (Sandbox Code Playgroud)
将返回[0,4],用(a[0],a[4]) = (1,5).
jam*_*lak 21
这样做的最好方法是制作b一个,set因为你只是检查其中的成员资格.
>>> a = [1, 2, 3, 4, 5]
>>> b = set([9, 7, 6, 5, 1, 0])
>>> [i for i, item in enumerate(a) if item in b]
[0, 4]
Run Code Online (Sandbox Code Playgroud)
def return_indices_of_a(a, b):
b_set = set(b)
return [i for i, v in enumerate(a) if v in b_set]
Run Code Online (Sandbox Code Playgroud)