比较python中的两个列表并返回匹配值的索引 [英] compare two lists in python and return indices of matched values

查看:612
本文介绍了比较python中的两个列表并返回匹配值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于两个列表a和b,如何获取两个列表中同时出现的值的索引?例如,

For two lists a and b, how can I get the indices of values that appear in both? For example,

a = [1, 2, 3, 4, 5]
b = [9, 7, 6, 5, 1, 0]

return_indices_of_a(a, b)

将返回[0,4],并带有(a[0],a[4]) = (1,5).

推荐答案

执行此操作的最佳方法是将b设置为set,因为您仅在其中检查成员资格.

The best way to do this would be to make b a set since you are only checking for membership inside it.

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

这篇关于比较python中的两个列表并返回匹配值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆