嵌套列表的索引

问题描述 投票:3回答:3

我正在尝试解决基因组比对项目中的一个问题。问题如下:如果给出嵌套列表

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中实现此目标的最佳方法是什么?提前致谢。

python python-3.x nested-lists indices
3个回答
6
投票

您可以创建一个字典(如果使用旧版python,则可以创建OrderedDict)。字典的键将是子列表的元组,而值将是索引数组。遍历之后,字典值将保留您的答案:

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]]

1
投票

您可以使用列表理解和范围来检查重复的索引,并将它们附加到result

result = []
for num in range(len(y)):
    occurances = [i for i, x in enumerate(y) if x == y[num]]
    if occurances not in result: result.append(occurances)

result
#[[0, 1, 7], [2], [3], [4, 5], [6]]

0
投票

考虑numpy解决此问题:

import numpy as np

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]
]

# Returns unique values of array, indices of that
# array, and the indices that would rebuild the original array
unique, indices, inverse = np.unique(y, axis=0, return_index=True, return_inverse=True)

这里是每个变量的打印内容:

unique = [
[1 2 3]
[1 2 8]
[3 4 5]
[4 2 5]
[6 5 4]]

indices = [0 6 2 4 3]

inverse = [0 0 2 4 3 3 1 0]

如果我们查看变量-inverse,我们可以看到确实确实获得了[0,1,7]作为我们第一个唯一元素[1,2,3]的索引位置,我们现在要做的就是将它们适当地分组。

new_list = []
for i in np.argsort(indices):
    new_list.append(np.where(inverse == i)[0].tolist()) 

输出:

new_list = [[0, 1, 7], [2], [3], [4, 5], [6]]

最后,引用上面的代码:

数字键-uniquewhereargsort

© www.soinside.com 2019 - 2024. All rights reserved.