嵌套列表中重复列表的索引

2024-04-19 05:51:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图解决一个问题,这是我基因组比对计划的一部分。问题如下: 如果给定一个嵌套列表

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中实现这一点的最佳方法是什么


Tags: 方法基因组列表计划正试图
3条回答

您可以创建一个字典(如果在较旧的python上,也可以创建OrderedDict)。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]]

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

如果我们查看变量-,我们可以看到我们确实得到了[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]]

最后,参考上述代码:

Numpy-uniquewhereargsort

您可以使用列表理解和范围来检查重复索引,并将它们附加到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]]

相关问题 更多 >