本文介绍了按值排序元组列表,然后按字母顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有点python新手,但我得到了以下元组列表.我需要按值对其进行排序,如果值相同,请按字母顺序解决关系.这是一个示例:

Bit of a python newbie, but I got the following list of tuples. I need to sort it by value and if the value is the same, solve ties alphabetically. Here's a sample:

#original
list_of_medals = [('Sweden', 24), ('Germany', 16), ('Russia', 10), ('Ireland', 10), ('Spain', 9), ('Albania', 8), ('Lithuania', 7), ('Iceland', 6), ('Malta', 5), ('Italy', 5), ('Serbia', 4), ('Estonia', 4), ('Turkey', 4), ('Moldova', 2), ('Azerbaijan', 2)]
#                                                              \____/                                                                                                                      \_____/                                         \______/
#after sorting                                                 /                                                                                                                          /                                              /
sorted_medals  = [('Sweden', 24), ('Germany', 16), ('Ireland', 10), ('Russia', 10), ('Spain', 9), ('Albania', 8), ('Lithuania', 7), ('Iceland', 6), ('Malta', 5), ('Italy', 5), ('Estonia', 4), ('Serbia', 4), ('Turkey', 4), ('Azerbaijan', 2), ('Moldova', 2)]

operator 模块是否可能?

推荐答案

可以使用sorted功能:

sorted_by_medals = sorted(list_of_medals, key=lambda tup: (-tup[1], tup[0]))

这篇关于按值排序元组列表,然后按字母顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 03:50