1

Code to retrieve i, v list:

 for i, v in enumerate(Some_array):
    print(i, v)

Output

0 -100
1 30
2 -90
3 -80
4 100
5 1000
and so on

Basically we have all the Vs as above 100, 30, -90 and so on. I want to sort the entire i,v in the order of v's from largest to smallest

Expected output

5 1000 
4 100
1 30
3 -80
2 -90
0 -100

I want the index values to remain the same. They should not get sorted. Only v values should be sorted. All other answers sort i values too and instead of 5,4,1,3,2,0 we get 0,1,2,3,4,5 as index which I dont want. Expected output is mentioned

noob
  • 3,601
  • 6
  • 27
  • 73
  • 1
    Use `for i, v in enumerate(sorted(Some_array, reverse=True)):` – jezrael Oct 19 '20 at 05:51
  • 1
    One problem, this above code sorts i too. I want i to stay the same and only v to be sorted. So I am getting 0,1,2,3,4,5 as i values corresponding to new v values, I want i values to be in this case 5,4,1,3,2,0 for instance. – noob Oct 19 '20 at 06:01

1 Answers1

1

Use sorted with enumerate(Some_array), lambda function and parameter reverse=True:

Some_array = [-100,30,-90,-80,100,1000]

for i, v in sorted(enumerate(Some_array), key=lambda tup: tup[1], reverse=True):
    print (i, v)
5 1000
4 100
1 30
3 -80
2 -90
0 -100

EDIT:

Some_array = [-100,30,-90,-80,100,1000]

topN = 3
for i, v in sorted(enumerate(Some_array), key=lambda tup: tup[1], reverse=True)[:topN]:
    print (i, v)
    5 1000
    4 100
    1 30
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252