Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an enumerated list by the value [duplicate]

MWE:

list1 = [2,5,46,23,9,78]
list1 = list(enumerate(list1))

Now suppose I want to sort this list by the index 1, i.e. by the original list1, in say, ascending order. How do I do that?

I would like something that could then give me both the indexes and the values.

list2 = sorted(list1[1], key=float)
like image 248
Euler_Salter Avatar asked Oct 25 '25 19:10

Euler_Salter


2 Answers

Sort with item[1] as key:

>>> list2 = sorted(list1, key=lambda x:x[1])
>>> list2
[(0, 2), (1, 5), (4, 9), (3, 23), (2, 46), (5, 78)]
like image 111
Uriel Avatar answered Oct 27 '25 10:10

Uriel


You need to pass in the whole list (not just the first element), and use a lambda function to sort on the value - x[1].

>>> list1 = [2,5,46,23,9,78]
>>> list2 = list(enumerate(list1))
>>> list2
[(0, 2), (1, 5), (2, 46), (3, 23), (4, 9), (5, 78)]
>>> list3 = sorted(list2, key=lambda x: x[1])
>>> list3
[(0, 2), (1, 5), (4, 9), (3, 23), (2, 46), (5, 78)]
like image 21
Attie Avatar answered Oct 27 '25 08:10

Attie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!