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


how sort list of strings key=len first key=str? i've tried following it's not giving me desired sort:

>>> ls = ['foo','bar','foobar','barbar'] >>>  >>> in sorted(ls): ...     print ...  bar barbar foo foobar >>> >>> in sorted(ls, key=len): ...     print ...  foo bar foobar barbar >>>  >>> in sorted(ls, key=str): ...     print ...  bar barbar foo foobar 

i need get:

bar foo barbar foobar 

define key function returns tuple in first item len(str) , second 1 string itself. tuples compared lexicographically. is, first lengths compared; if equal strings compared.

in [1]: ls = ['foo','bar','foobar','barbar']  in [2]: sorted(ls, key=lambda s: (len(s), s)) out[2]: ['bar', 'foo', 'barbar', 'foobar'] 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -