Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the original indexes after sorting a list in python

Tags:

python

I have a list as follows.

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

I want to get the indexes of the top 4 elements of the list (i.e [5, 9, 3, 8]) and remove the indexes that have a value lesser than or equal to 1 (<=1).

Therefore my final output should be [5, 9]

My current code is as follows:

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

However, it returns [5, 5], which is incorrect.

Please let me know how I can fix this in python?

like image 644
J Cena Avatar asked Dec 07 '22 15:12

J Cena


2 Answers

You should use 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]
like image 135
Patrick Haugh Avatar answered May 03 '23 14:05

Patrick Haugh


You can sort the list along with the index, so that the index is easily retrieved later like:

Code:

sorted_mylist = sorted(((v, i) for i, v in enumerate(mylist)), reverse=True)

Test Code:

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

sorted_mylist = sorted(((v, i) for i, v in enumerate(mylist)), reverse=True)
result = []
for i, (value, index) in enumerate(sorted_mylist):
    if i == 4:
        break
    if value > 1:
        result.append(index)

print(result)

Results:

[9, 5]
like image 36
Stephen Rauch Avatar answered May 03 '23 15:05

Stephen Rauch