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
Post a Comment