python - 在 Python 中按不同级别排序

标签 python list sorting

我正在尝试对这样的元组列表进行排序:

[('Pineapple', 1), ('Orange', 3), ('Banana', 1), ('Apple', 1), ('Cherry', 2)]

排序后的列表应该是:

[('Orange', 3), ('Cherry', 2), ('Apple', 1), ('Banana', 1), ('Pineapple', 1)]

因此,这里第一个列表应该基于 tuple[1] 降序排序,然后如果 tuple 值(tuple[1]) 像 AppleBananaPineapple 一样匹配 - 列表应该根据 tuple[0]按升序排列。

我已经尝试了可能的方法-

top_n.sort(key = operator.itemgetter(1, 0), reverse = True)
# Output: [(Orange, 3), (Cherry, 2), (Pineapple, 1), (Banana, 1), (Apple, 1)]

作为 “reverse = True”,菠萝,然后是香蕉,...

我终于想出了一个解决办法:

top_n.sort(key = operator.itemgetter(0), reverse = False)
top_n.sort(key = operator.itemgetter(1), reverse = True)

有没有像我的第一种方法那样更好的方法来获得解决方案。我正在尝试更多地探索 Python,从而寻求这样的解决方案。

最佳答案

让您的 key 返回数值取反 的元组,然后是字符串。通过否定,您的数字将按降序排序,而字符串按升序排序:

top_n.sort(key=lambda t: (-t[1], t[0]))

是的,这有点 hack,但适用于任何需要按相反方向的两个标准进行排序的地方,其中一个标准是数字。

演示:

>>> top_n = [('Pineapple', 1), ('Orange', 3), ('Banana', 1), ('Apple', 1), ('Cherry', 2)]
>>> sorted(top_n, key=lambda t: (-t[1], t[0]))
[('Orange', 3), ('Cherry', 2), ('Apple', 1), ('Banana', 1), ('Pineapple', 1)]

关于python - 在 Python 中按不同级别排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34784220/

相关文章:

python - Scrapy延迟请求

c++ - 如何在 C++ 中对包含动态数组的结构数组进行排序?

python - 检查 Python 列表中是否有(不)某些东西

c++ - 梳状排序在 C++ 中不起作用

java - 递归选择排序 (Java Eclipse Neon 2)

python - isinstance() 和 issubclass() 返回冲突的结果

python - 在优化方法中将 numpy ndarray 转换为元组的元组

python - 值错误 : array is too big

Jquery 无法排序并将大项目拖到底部

python - 从列表中运行函数