Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify 2 keys in python sorted(list)?

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
like image 313
alvas Avatar asked May 13 '13 06:05

alvas


People also ask

How do you sort multiple keys in a Dictionary Python?

Sort by multiple keys Two dictionaries have the value 'CA' for the key 'State' . If the values are equal, the original order is preserved. You can specify multiple arguments for operator. itemgetter() , and if the values for the first key are equal, they will be compared and sorted by the value of the next key.

How do you sort multiple elements in a list Python?

To sort a list of tuples by multiple elements in Python: Pass the list to the sorted() function. Use the key argument to select the elements at the specific indices in each tuple. The sorted() function will sort the list of tuples by the specified elements.

How do you sort a list in sorted Python?

Python sorted() FunctionThe sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.


2 Answers

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.

In [1]: ls = ['foo','bar','foobar','barbar']

In [2]: sorted(ls, key=lambda s: (len(s), s))
Out[2]: ['bar', 'foo', 'barbar', 'foobar']
like image 79
root Avatar answered Oct 14 '22 01:10

root


The answer from root is correct, but you don't really need a lambda:

>>> def key_function(x):
        return len(x), str(x)

>>> sorted(['foo','bar','foobar','barbar'], key=key_function)
['bar', 'foo', 'barbar', 'foobar']

In addtion, there is a alternate approach takes advantage of sort stability which lets you sort in multiple passes (with the secondary key first):

>>> ls = ['foo','bar','foobar','barbar']
>>> ls.sort(key=str)                       # secondary key
>>> ls.sort(key=len)                       # primary key

See the Sorting HOWTO for a good tutorial on Python sorting techniques.

like image 21
Raymond Hettinger Avatar answered Oct 14 '22 00:10

Raymond Hettinger