python - python : get indices of a sub-list in a larger list 中的列表匹配

标签 python list set match indices

对于两个列表,

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/

相关文章:

r - 在 lapply 中指定列表元素的长度作为索引

Java:最好将实体中的列表初始化为空列表或空列表

python - 从静态方法调用非静态方法

java - 无法使用 SSL 在 java 客户端和 python 服务器之间执行通信

python - scrapy 数据库插入失败但没有错误

python - Python中一组列表的所有可能排列

Python 搁置错误 - 声明 NoneType,但对象 * 存在 * 在那里

python - 合并具有共同元素的集合?

c++ - 如何创建一个 std::set 结构?

python - 比较 Python 字典中保存的集合