0

I want to sort a list in this form:

[('Initial value problem', 0.0), 
 ('Duns Scotus', 0.0), 
 ('Open front unrounded vowel', 0.0), 
 ('Android version history', 0.0001), 
 ('Research ethics', 0.0001), 
 ('Music technology', 0.0), 
 ('Karl Bechert', 0.0001), 
 ('Motion (physics)', 0.0001), 
 ('Karl Friedrich Burdach', 0.0)]

And I want to sort this list based on the number in each element. Thanks.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
epx
  • 571
  • 4
  • 16
  • 27
  • @mins. Because at first I have no idea where to start to solve this question. – epx Apr 14 '15 at 08:15
  • possible duplicate of [How to sort (list/tuple) of lists/tuples?](http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – mins Apr 14 '15 at 08:29
  • @mins Thanks for telling me this. – epx Apr 16 '15 at 01:58

1 Answers1

2

Just sort on the 2nd element of each item by setting the key parameter

>>> l = [('Initial value problem', 0.0), 
     ('Duns Scotus', 0.0), 
     ('Open front unrounded vowel', 0.0), 
     ('Android version history', 0.0001), 
     ('Research ethics', 0.0001), 
     ('Music technology', 0.0), 
     ('Karl Bechert', 0.0001), 
     ('Motion (physics)', 0.0001), 
     ('Karl Friedrich Burdach', 0.0)]

>>> print sorted(l, key=lambda x: x[1])

[('Initial value problem', 0.0),
 ('Duns Scotus', 0.0),
 ('Open front unrounded vowel', 0.0),
 ('Music technology', 0.0),
 ('Karl Friedrich Burdach', 0.0),
 ('Android version history', 0.0001),
 ('Research ethics', 0.0001),
 ('Karl Bechert', 0.0001),
 ('Motion (physics)', 0.0001)]

If you want them in the opposite order, also set reverse=True parameter in the call to sorted()

Tim
  • 41,901
  • 18
  • 127
  • 145