2

So I have a list that looks something like this:

example = [['b',1],['b',2],['a',2]]

And it needs to be sorted to become:

example = [['b',1],['a',2],['b',2]]

I.e. sorted numerically by the number in the [1] position. The program needs to recognise when there are two numbers that are the same, and then sort these elements alphabetically.

Any ideas?

Edit:

and how would I go about sorting the list so that the highest number is printed first?, i.e:

example = [['a',2],['b',2],['b',1]]
Hayley van Waas
  • 429
  • 3
  • 12
  • 21

3 Answers3

5

You can use list.sort, its key function, and operator.itemgetter:

>>> from operator import itemgetter
>>> example = [['b',1],['b',2],['a',2]]
>>> example.sort(key=itemgetter(1,0))
>>> example
[['b', 1], ['a', 2], ['b', 2]]
>>>

You could also use a lambda instead of operator.itemgetter:

example.sort(key=lambda x: (x[1], x[0]))

but that would be slower.

  • Could you explain how this works? Lets say I now wanted to sort the list from the highest number to the lowest (but still sorting elements with the same number alphabetically a-z), how would you change this code to allow for that? – Hayley van Waas Feb 12 '14 at 04:49
  • @HayleyvanWaas, I've got examples for that in my answer – John La Rooy Feb 12 '14 at 04:56
3
>>> lis = [['b',1],['b',2],['a',2]]
>>> sorted(lis, key=lambda x:x[::-1])
[['b', 1], ['a', 2], ['b', 2]]

To sort the list in-place use lis.sort(...).

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
3

Here is a neat trick

>>> example = [['b',1],['b',2],['a',2]]
>>> sorted(example, key=sorted)
[['b', 1], ['a', 2], ['b', 2]]

Only works for Python2 though


There are two ways to sort by numbers from highest to lowest

>>> sorted(example, key=lambda x: (-x[1], x[0]))
[['a', 2], ['b', 2], ['b', 1]]

or

>>> from operator import itemgetter
>>> sorted(sorted(example), key=itemgetter(1), reverse=True)
[['a', 2], ['b', 2], ['b', 1]]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502