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

2024-10-06 06:59:38 发布

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

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

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]

输出应为:

^{pr2}$

其中,[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

Tags: in元素列表forif排序not数字
1条回答
网友
1楼 · 发布于 2024-10-06 06:59:38

给你:

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

基于一些非常基本的测试,它的速度大约是你发布的代码的两倍。在

相关问题 更多 >