在python中对列表进行排序后如何获取原始索引

J C*_*ena 3 python

我的清单如下。

mylist= [0.0, 0.4, 0.81, 1.0, 0.9, 20.7, 0.0, 0.8, 1.0, 20.7]
Run Code Online (Sandbox Code Playgroud)

我想获取列表中前4个元素的索引(即[5, 9, 3, 8]),并删除值小于或等于1(<=1)的索引。

因此,我的最终输出应该是 [5, 9]

我当前的代码如下:

sorted_mylist = sorted(mylist, reverse = True)[:4]
for ele in sorted_mylist:
    if ele>1:
       print(mylist.index(ele))
Run Code Online (Sandbox Code Playgroud)

但是,它返回[5, 5],这是不正确的。

请让我知道如何在python中解决此问题?

Pat*_*ugh 6

你应该用 enumerate

mylist= [0.0, 0.4, 0.81, 1.0, 0.9, 20.7, 0.0, 0.8, 1.0, 20.7]

indices = [index for index, value in sorted(enumerate(mylist), reverse=True, key=lambda x: x[1]) if value > 1][:4]
# [5, 9]
Run Code Online (Sandbox Code Playgroud)