首页 > 解决方案 > 如何从列表中的最大数字到最小数字获取索引?

问题描述

我正在用 Python 编写一个小项目:

我想从以下列表中从最高到最小的数字获取索引(在列表中):

list = [20, 30, 24, 26, 22, 10]

结果应该是:

index_list = [1, 3, 2, 4, 0, 5]

任何人都知道我该怎么做?提前致谢。

标签: pythonlistindexingmaxmin

解决方案


我对python编程很陌生,但这似乎可行:

list = [20, 30, 24, 26, 22, 10]
list_sorted = list.copy()
list_sorted.sort()

list_index = []
for x in list_sorted:
    list_index.insert(0,list.index(x))

print(list_index)

输出:

[1, 3, 2, 4, 0, 5]

因为上面会产生不正确的值,所以存在重复,请参见下一个:

list = [20, 10, 24, 26, 22, 10]
list_tmp = list.copy()
list_sorted = list.copy()
list_sorted.sort()

list_index = []
for x in list_sorted:
    list_index.insert(0,list_tmp.index(x))
    list_tmp[list_tmp.index(x)] = -1

print(list)
print(list_index)

输出:

[20, 10, 24, 26, 22, 10]
[3, 2, 4, 0, 5, 1]

输出是否[3, 2, 4, 0, 5, 1][3, 2, 4, 0, 1, 5]因为这些索引引用相同的值无关紧要。


推荐阅读