对于两个列表,
a = [1, 2, 9, 3, 8, ...] (no duplicate values in a, but a is very big)
b = [1, 9, 1,...] (set(b) is a subset of set(a), 1<<len(b)<<len(a))
indices = get_indices_of_a(a, b)
如何让 get_indices_of_a
返回 indices = [0, 2, 0,...]
和 array(a)[indices] = b
?有没有比使用花费太长时间的 a.index
更快的方法?
使 b
成为一个集合是匹配列表和返回索引的快速方法(参见 compare two lists in python and return indices of matched values ),但它也会丢失第二个 1
的索引作为本例中索引的序列。
最佳答案
一个快速的方法(当 a
是一个大列表时)是使用字典将 a
中的值映射到索引:
>>> index_dict = dict((value, idx) for idx,value in enumerate(a))
>>> [index_dict[x] for x in b]
[0, 2, 0]
与使用 a.index
相比,这在平均情况下需要线性时间,后者需要二次时间。
关于python - python : get indices of a sub-list in a larger list 中的列表匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10385647/