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

后端 未结 4 597
我在风中等你
我在风中等你 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:32

    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']
    

提交回复
热议问题