繁体   English   中英

在从max到min元素开始的大量整数列表中查找元素索引的有效方法

[英]Efficient way to find index of elements in a large list of integers starting with max to min elements

我有大量未排序整数 ,数字可能重复。 我想创建另一个列表,该列表是从第一个列表开始的索引子列表的列表,从最大元素到最小,以降序排列。 例如,如果我有一个这样的列表:

list = [4, 1, 4, 8, 5, 13, 2, 4, 3, 7, 14, 4, 4, 9, 12, 1, 6, 14, 10, 8, 6, 4, 11, 1, 2, 11, 3, 9]

输出应为:

indexList = [[10, 17], [5], [14], [22, 25], [18], [13, 27], [3, 19], [9], [16, 20], [4], [0, 2, 7, 11, 12, 21], [8, 26], [6, 24], [1, 15, 23]]

其中, [10, 17]是存在“ 14 ”的位置的索引,依此类推...

在下面共享了我的代码。 使用cProfile对大约9000个元素的列表进行分析大约需要6秒钟。

def indexList(list):
    # List with sorted elements
    sortedList = sorted(list, reverse = True)

    seen = set()
    uSortedList = [x for x in sortedList if x not in seen and not seen.add(x)]

    indexList = []
    for e in uSortedList:
        indexList.append([i for i, j in enumerate(list) if j == e])

    return indexList

干得好:

def get_list_indices(ls):
    indices = {}
    for n, i in enumerate(ls):
        try:
            indices[i].append(n)
        except KeyError:
            indices[i] = [n]
    return [i[1] for i in sorted(indices.items(), reverse=True)]

test_list = [4, 1, 4, 8, 5, 13, 2, 4, 3, 7, 14, 4, 4, 9, 12, 1, 6, 14, 10, 8, 6, 4, 11, 1, 2, 11, 3, 9]
print(get_list_indices(test_list))

根据一些非常基本的测试,它的速度大约是您发布的代码的两倍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM