【发布时间】:2019-02-27 15:47:14
【问题描述】:
Python 代码:
b=['six', 'small', 'he', 'foxes', 'saw']
b.sort(key=len)
b
输出:
['he', 'six', 'saw', 'small', 'foxes']
在上面的代码中,我按照元素的长度排序,得到了上面的输出。
我想要的输出是这样的:['he', 'saw', 'six', 'small', 'foxes']
所以我想要第一个按长度排序。然后对于长度相同的元素,我想按字母顺序排序。
我的问题:有没有办法在不编写自定义函数的情况下做到这一点?也许是这样的:
b.sort(key=[len,sorted]) # this doesn't work but I think it explains the idea.
谢谢!
【问题讨论】:
-
Then for elements with the same length I want to sort alphabetically.-- 这是不是应该是['he', 'saw', 'six', 'foxes', 'small'] -
描述的顺序应该是:
['he', 'saw', 'six', 'foxes', 'small']