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排序元组列表


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01