0

I want to sort this list:

>>> L = ['A', 'B', 'C', ... 'Z', 'AA', 'AB', 'AC', ... 'AZ', 'BA' ...]

Exactly the way it is, regardless of the contents (assuming all CAPS alpha).

>>> L.sort()
>>> L
['A', 'AA', 'AB', 'AC'...]

How can I make this:

>>> L.parkinglot_sort()
>>> L
['A', 'B', 'C', ... ]

I was thinking of testing for length, and sorting each length, and mashing all the separate 1-length, 2-length, n-length elements of L into the new L.

Thanks!

yurisich
  • 6,991
  • 7
  • 42
  • 63
  • Ref : http://stackoverflow.com/questions/4659524/how-to-sort-by-length-of-string-followed-by-alphabetical-order I think it is that you want :) J. – Jeremy D Dec 16 '11 at 17:02

1 Answers1

6

What about this?

l.sort(key=lambda element: (len(element), element))

It will sort the list taking into account not only each element, but also its length.

>>> l = ['A', 'AA', 'B', 'BB', 'C', 'CC']
>>> l.sort(key=lambda element: (len(element), element))
>>> print l
['A', 'B', 'C', 'AA', 'BB', 'CC']
jcollado
  • 39,419
  • 8
  • 102
  • 133
  • Oh hey...an anonymous function to do the measurement before sorting... *lambda statement flying over head* – yurisich Dec 16 '11 at 17:03