[英]Efficient way to find index of elements in a large list of integers starting with max to min elements
I have a large list of integers unsorted , numbers might be duplicated. 我有大量未排序的整数 ,数字可能重复。 I would like to create another list which is a list of sub-lists of indexes from the first list starting with max element to min, in decreasing order. 我想创建另一个列表,该列表是从第一个列表开始的索引子列表的列表,从最大元素到最小,以降序排列。 For example, if I have a list like this: 例如,如果我有一个这样的列表:
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]
The output should be: 输出应为:
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]]
where, [10, 17]
is the index of where ' 14
' is present and so on... 其中, [10, 17]
是存在“ 14
”的位置的索引,依此类推...
Shared my code below. 在下面共享了我的代码。 Profiling it using cProfile for a list of around 9000 elements takes around ~6 seconds. 使用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
Here you go: 干得好:
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))
Based on some very basic testing, it is about twice as fast as the code you posted. 根据一些非常基本的测试,它的速度大约是您发布的代码的两倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.