python排序元组列表

python sort list of tuple(python排序元组列表)
本文介绍了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排序元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)