简体   繁体   English

如何让python按字母顺序打印出列表中的元素?

[英]How can I let python print out the elements in a list in alphabetical order?

So I wrote this code to return every string in a list in the order of word length.所以我写了这段代码,按照字长的顺序返回列表中的每个字符串。

def sort_by_length(words: list[str]):
    return sorted(words, key=len)
print(sort_by_length(['this','is','a','test','for','sorting','by','length']))

and I get the output, which is我得到输出,即

['a', 'is', 'by', 'for', 'this', 'test', 'length', 'sorting']

However, I want to change my code a bit so that if two or more strings has the same length, the code will return both the strings but in alphabetical order.但是,我想稍微更改我的代码,以便如果两个或多个字符串具有相同的长度,代码将返回两个字符串,但按字母顺序排列。

So like from the output that I get, I want it to be like:所以就像我得到的输出一样,我希望它是这样的:

['a', 'by', 'is', 'for', 'this', 'test', 'length', 'sorting']

What should I change?我应该改变什么?

Use a key function that returns a tuple.使用返回元组的键函数。

def sort_by_length(words: list[str]):
    return sorted(words, key=lambda x: (len(x), x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM