【问题标题】:How to sort a python list bidirectionally, by numbers in descending order and by alphabets in ascending order? [duplicate]如何按数字降序和字母升序对python列表进行双向排序? [复制]
【发布时间】:2014-09-04 02:59:19
【问题描述】:

我正在尝试对包含由单词和数字组成的元组的列表进行排序。

my_list = [('hello',25), ('hell',4), ('bell',4)]

我怎样才能对它进行排序(也许使用 lambda)以便我得到

[('hello',25), ('bell',4), ('hell',4)]

【问题讨论】:

  • 您能解释一下您面临的问题吗?

标签: python sorting


【解决方案1】:

最简单的方法是利用sort stability 并分两遍进行排序:

>>> lot = [('hello', 25), ('hell', 4), ('bell', 4)]
>>> lot.sort(key=lambda r: r[0])
>>> lot.sort(key=lambda r: r[1], reverse=True)
>>> lot
[('hello', 25), ('bell', 4), ('hell', 4)]

您也可以使用sorted()

>>> lot = [('hello', 25), ('hell', 4), ('bell', 4)]
>>> sorted(sorted(lot, key=lambda r: r[0]), key=lambda r: r[1], reverse=True)
[('hello', 25), ('bell', 4), ('hell', 4)]

这是 Python 的 Sorting Howto 指南中推荐的技术。

【讨论】:

    【解决方案2】:

    您可以在 key 参数中将 sorted 转换为您想要的顺序。

    x = [('hello',25),('hell',4),('bell',4)]
    
    sorted(x, key = lambda tup: (-tup[1], tup[0]))
    Out[15]: [('hello', 25), ('bell', 4), ('hell', 4)]
    

    【讨论】:

    • 虽然这在这种情况下有效,但它不是一个适用于其他情况的通用解决方案。 (例如,您不能使用该技术对字符串进行降序排序;它仅适用于数字)。
    猜你喜欢
    • 2022-01-09
    • 2021-12-19
    • 2021-06-09
    • 2018-01-14
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 2016-10-18
    相关资源
    最近更新 更多