0

I am trying to sort a list of tuples by the the second value but don't know how to.

This is a sample of the list.

[(0, 0.008419530634828806),
 (1, 0.025931516073376813),
 (2, 0.028300978579639452),
 (3, 0.0290595847459555),
 (4, 0.010301903453003166),
 (5, 0.3762918396584051),
 (6, 0.1081064920744848),
 (7, 0.013774706789176786),
 (8, 0.0002836788948967922),
 (9, 0.23690695321179311),
 (10, 0.007678502309668166),
 (11, 0.004393399463184975),
 (12, 0.015535320262138509),
 (13, 0.005949274957664495)]

I know I can extract the second column and use np.sort() but I want to maintain the tuple format so I can have the index value attached to each float. Is there a way to go about doing this?

Ji Pak
  • 3
  • 1

1 Answers1

0
my_list = [(0, 0.008419530634828806),
 (1, 0.025931516073376813),
 (2, 0.028300978579639452),
 (3, 0.0290595847459555),
 (4, 0.010301903453003166),
 (5, 0.3762918396584051),
 (6, 0.1081064920744848),
 (7, 0.013774706789176786),
 (8, 0.0002836788948967922),
 (9, 0.23690695321179311),
 (10, 0.007678502309668166),
 (11, 0.004393399463184975),
 (12, 0.015535320262138509),
 (13, 0.005949274957664495)]

sorted_list = sorted(my_list,key=lambda x:x[1])
print(sorted_list)
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39