python排序元组列表

2022-01-20 00:00:00 python list tuples sorting

问题描述

我正在尝试对元组列表进行排序.例如,如果

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

相关文章