【问题标题】:outputting a list in order of shortest word to longest word (python) [duplicate]按最短单词到最长单词的顺序输出列表(python)[重复]
【发布时间】:2012-04-12 07:22:43
【问题描述】:

可能重复:
how to sort by length of string followed by alphabetical order?

我想创建一个程序,按照从最短到最长字符数的顺序打印列表中的单词。例如:

["My", "turtle", "is", "old"]

会输出:

"My"
"is"
"old"
"turtle"

有什么简单的方法可以做到这一点吗?我到目前为止:

message = "My turtle is old"
message = message.split(" ")

【问题讨论】:

标签: python


【解决方案1】:

使用 .sort()key 关键字按长度对输入进行排序:

l = ["My", "turtle", "is", "old"]
l.sort(key=len)

for i in l:
  print i

【讨论】:

    【解决方案2】:
    l = ["My", "turtle", "is", "old"]
    l.sort(key=len, reverse=True)
    # -> ['turtle', 'old', 'My', 'is']
    

    您可能希望查看有关该主题的 Python wiki:http://wiki.python.org/moin/HowTo/Sorting

    【讨论】:

    • 不用reverse=True试试看。
    最近更新 更多