3

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)
Euler_Salter
  • 3,271
  • 8
  • 33
  • 74
  • If it's an option, consider sorting the list before enumerating it: `list(enumerate(sorted(list1)))`, unless you intend to keep a reference to the original index, in which case this does not work. –  Jul 10 '17 at 16:25

3 Answers3

8

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)]
Uriel
  • 15,579
  • 6
  • 25
  • 46
3

Something like this?

>>> from operator import itemgetter
>>> sorted(list1, key=itemgetter(1))
[(0, 2), (1, 5), (4, 9), (3, 23), (2, 46), (5, 78)]

By providing a function of one argument to key we are specifying a comparison key for list elements used by sorted. itemgetter is a nice functional wrapper around item getter operator [i].

randomir
  • 17,989
  • 1
  • 40
  • 55
2

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)]
Attie
  • 6,690
  • 2
  • 24
  • 34