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

后端 未结 4 614
我在风中等你
我在风中等你 2021-01-17 10:50

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:



        
4条回答
  •  长发绾君心
    2021-01-17 11:34

    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.

提交回复
热议问题