sin*_*uja 3 python performance nested-lists indices
我正在尝试解决属于我的基因组比对项目一部分的问题。问题如下:如果给定一个嵌套列表
y = [[1,2,3],[1,2,3],[3,4,5],[6,5,4],[4,2,5],[4,2,5],[1,2,8],[1,2,3]]
再次将唯一列表的索引提取到嵌套列表中。
例如,上面嵌套列表的输出应该是
[[0,1,7],[2],[3],[4,5],[6]].
这是因为列表[1,2,3]存在于0,1,7th索引位置、[3,4,5]第二索引位置等。
由于我将处理大型列表,那么在 Python 中实现这一目标的最佳方法是什么?
你可以创建一个字典(或者 OrderedDict 如果在旧的 python 上)。dict 的键是子列表的元组,值是索引数组。循环后,字典值将保存您的答案:
from collections import OrderedDict
y = [[1,2,3],[1,2,3],[3,4,5],[6,5,4],[4,2,5],[4,2,5],[1,2,8],[1,2,3]]
lookup = OrderedDict()
for idx,l in enumerate(y):
lookup.setdefault(tuple(l), []).append(idx)
list(lookup.values())
# [[0, 1, 7], [2], [3], [4, 5], [6]]
Run Code Online (Sandbox Code Playgroud)