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)
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)]
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With