python – 按值排序元组列表,然后按字母顺序排序

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

#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)]

是否可能使用运算符模块?

您可以使用已排序的函数:

sorted_by_medals = sorted(list_of_medals, key=lambda tup: (-tup[1], tup[0]))
https://stackoverflow.com/questions/13482313/sort-a-list-of-tuples-by-value-and-then-alphabetically

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 按值排序元组列表,然后按字母顺序排序