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排序元组列表
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
