python元组排序列表 [英] python sort list of tuple

查看:48
本文介绍了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!

推荐答案

您可以传递要排序的密钥:

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).出色的排序方法

Note that Cameron Tucker comes before Manny Delgado now. All this and more is covered in detail in the excellent Sorting Howto

这篇关于python元组排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆