【问题标题】:How can I let python print out the elements in a list in alphabetical order?如何让python按字母顺序打印出列表中的元素?
【发布时间】: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']

我应该改变什么?

【问题讨论】:

    标签: python list tuples


    【解决方案1】:

    使用返回元组的键函数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多