python sort list of tuple(python排序元组列表)
问题描述
我正在尝试对元组列表进行排序.例如,如果
I am trying to sorting a list of tuple. for example, If
>>>recommendations = [('Gloria Pritchett', 2), ('Manny Delgado', 1), ('Cameron Tucker', 1), ('Luke Dunphy', 3)]
我想得到
Luke Dunphy
Gloria Pritchett
Cameron Tucker
Manny Delgado
这就是我所做的:
这段代码只给了我
>>> [('Luke Dunphy', 3), ('Gloria Pritchett', 2), ('Cameron Tucker', 1), ('Manny Delgado', 1)]
我不知道如何在 sorted_list 中仅附加名称(字符串).请帮忙!
I have no idea how to append only names(strings) in sorted_list. Please help!
推荐答案
可以传入key进行排序:
You can pass in the key to sorted:
>>> s = sorted(recommendations, key=lambda x: x[1], reverse=True)
[('Luke Dunphy', 3), ('Gloria Pritchett', 2), ('Manny Delgado', 1), ('Cameron Tucker', 1)]
然后获取名称:
names = [x[0] for x in s]
# ['Luke Dunphy', 'Gloria Pritchett', 'Manny Delgado', 'Cameron Tucker']
如果您已经注意到,Manny Delgado 和 Cameron Tucker 基于他们的键 (1) 并列,但 Manny Delgado 排在 Cameron Tucker 之前,因为 python 排序是就地.但是,根据您所需的输出,您希望使用辅助键(在本例中为名称)解决主键中的关系.您可以通过 first 按名称排序并 then 按主整数键排序来做到这一点:
If you've noticed, Manny Delgado and Cameron Tucker are tied based on their key(1), but Manny Delgado comes before Cameron Tucker, because python sorting is in-place. However, based on your desired output, you want the ties in primary key to be resolved using the secondary key (the name in this case). You can do this by first sorting by name and then sorting by the primary integer key:
t = sorted(recommendations, key=lambda x: x[0])
s = sorted(t, key=lambda x: x[1], reverse=True)
# [('Luke Dunphy', 3), ('Gloria Pritchett', 2), ('Cameron Tucker', 1), ('Manny Delgado', 1)]
请注意,Cameron Tucker 现在排在 Manny Delgado 之前.优秀的 Sorting Howto
Note that Cameron Tucker comes before Manny Delgado now. All this and more is covered in detail in the excellent Sorting Howto
这篇关于python排序元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python排序元组列表


基础教程推荐
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01