How do I sort a list of strings by key=len
first then by key=str
?
I've tried the following but it's not giving me the desired sort:
>>> ls = ['foo','bar','foobar','barbar']
>>>
>>> for i in sorted(ls):
... print i
...
bar
barbar
foo
foobar
>>>
>>> for i in sorted(ls, key=len):
... print i
...
foo
bar
foobar
barbar
>>>
>>> for i in sorted(ls, key=str):
... print i
...
bar
barbar
foo
foobar
I need to get:
bar
foo
barbar
foobar
If you don't want to use lambda:
Define a key function that returns a tuple in which the first item is
len(str)
and the second one is the string itself. Tuples are then compared lexicographically. That is, first the lengths are compared; if they are equal then the strings get compared.Another form that works without a lambda:
The answer from root is correct, but you don't really need a lambda:
In addtion, there is a alternate approach takes advantage of sort stability which lets you sort in multiple passes (with the secondary key first):
See the Sorting HOWTO for a good tutorial on Python sorting techniques.