Question

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!

Was it helpful?

Solution

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']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top