0

I need to reorder a Python list according to the second element of embedded lists:

So this:

[[1, 'A'], [2, 'B'], [3, 'B'], [4, 'A'], [5, 'C']]

Should turn into that:

[[1, 'A'], [4, 'A'], [2, 'B'], [3, 'B'], [5, 'C']]

I am struggling with this piece of code right now:

values = set(map(lambda x:x[1], l))
l = [[y[0] for y in l if y[1]==x] for x in values]

What the most straightforward way to accomplish this?

Lucien S.
  • 5,123
  • 10
  • 52
  • 88

3 Answers3

4

Using the built-in function sorted:

>>> l = [[1, 'A'], [2, 'B'], [3, 'B'], [4, 'A'], [5, 'C']]
>>> from operator import itemgetter
>>> sorted(l, key=itemgetter(1))
[[1, 'A'], [4, 'A'], [2, 'B'], [3, 'B'], [5, 'C']]
eskaev
  • 1,108
  • 6
  • 11
2

Like this:

>>> def getKey(item):
...     return item[1]
>>> l = [[1, 'A'], [2, 'B'], [3, 'B'], [4, 'A'], [5, 'C']]
>>> sorted(l, key=getKey)
[[1, 'A'], [4, 'A'], [2, 'B'], [3, 'B'], [5, 'C']]
FBruynbroeck
  • 499
  • 3
  • 15
1

First sort in reverse by the first, and the sort by the second...

L = [[1, 'A'], [2, 'B'], [3, 'B'], [4, 'A'], [5, 'C']]
L.sort(key=lambda sublist: sublist[0], reverse=True)
L.sort(key=lambda sublist: sublist[1])
TheLazyScripter
  • 2,541
  • 1
  • 10
  • 19