python中的列表匹配:在更大的列表中获取子列表的索引 [英] list match in python: get indices of a sub-list in a larger list

查看:126
本文介绍了python中的列表匹配:在更大的列表中获取子列表的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于两个列表,

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_aarray(a)[indices] = b返回indices = [0, 2, 0,...]?是否有比使用a.index的方法更快的方法,该方法花费的时间太长?

how to let get_indices_of_a return indices = [0, 2, 0,...] with array(a)[indices] = b? Is there a faster method than using a.index, which is taking too long?

b设为集合是匹配列表并返回索引的快速方法(请参阅比较python中的两个列表并返回的索引)匹配的值),但是在这种情况下,它将丢失第二个1的索引以及索引的顺序.

Making b a set is a fast method of matching lists and returning indices (see compare two lists in python and return indices of matched values ), but it will lose the index of the second 1 as well as the sequence of the indices in this case.

推荐答案

一种快速方法(当a是一个很大的列表时)将使用字典将a中的值映射到索引:

A fast method (when a is a large list) would be using a dict to map values in a to indices:

>>> index_dict = dict((value, idx) for idx,value in enumerate(a))
>>> [index_dict[x] for x in b]
[0, 2, 0]

与使用a.index需要二次时间的情况相比,在一般情况下,这将花费线性时间.

This will take linear time in the average case, compared to using a.index which would take quadratic time.

这篇关于python中的列表匹配:在更大的列表中获取子列表的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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