compare two lists in python and return indices of matched values

夙愿已清 提交于 2019-12-17 19:35:04

问题


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)

would return [0,4], with (a[0],a[4]) = (1,5).


回答1:


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]



回答2:


def return_indices_of_a(a, b):
  b_set = set(b)
  return [i for i, v in enumerate(a) if v in b_set]



回答3:


For larger lists this may be of help:

for item in a:
index.append(bisect.bisect(b,item))
    idx = np.unique(index).tolist()

Be sure to import numpy.



来源:https://stackoverflow.com/questions/10367020/compare-two-lists-in-python-and-return-indices-of-matched-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!