【发布时间】:2021-11-13 06:27:05
【问题描述】:
所以我写了这段代码,按照字长的顺序返回列表中的每个字符串。
def sort_by_length(words: list[str]):
return sorted(words, key=len)
print(sort_by_length(['this','is','a','test','for','sorting','by','length']))
我得到了输出,即
['a', 'is', 'by', 'for', 'this', 'test', 'length', 'sorting']
但是,我想稍微更改一下我的代码,以便如果两个或多个字符串具有相同的长度,代码将返回两个字符串,但按字母顺序。
所以就像我得到的输出一样,我希望它是这样的:
['a', 'by', 'is', 'for', 'this', 'test', 'length', 'sorting']
我应该改变什么?
【问题讨论】: