python 使用 sorted 对 列表嵌套元组的数据进行排序

Posted lowmanisbusy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用 sorted 对 列表嵌套元组的数据进行排序相关的知识,希望对你有一定的参考价值。

在开发的过程可能会遇到这么一个需求,存在一个列表嵌套元组的数据:

data = [(1, a),(2, b),(5, c),(3, d),(4, e)]

需要将这个列表按照元组的第一个或者第二个元素进行排序, 这时可以直接使用内置函数sorted()进行处理

1.按照第一个元素的大小进行排序

new_data = sorted(data)
print(new_data)

输出:

[(1, a), (2, b), (3, d), (4, e), (5, c)]

 

2.按照第二个元素的大小进行排序

先将元组的元素进行倒转:

data = [(1, a),(5, ‘c),(2, ‘b),(3, d),(4, e)]
new_list = []
for item in data:
    new_list.append(item[::-1])
print(new_list)

输出:

[(a, 1), (‘c, 5), (‘b, 2), (d, 3), (e, 4)]

然后再进行排序:

new_data = sorted(new_list)
print(new_data)

输出:

[(a, 1), (b, 2), (c, 5), (d, 3), (e, 4)]

 


以上是关于python 使用 sorted 对 列表嵌套元组的数据进行排序的主要内容,如果未能解决你的问题,请参考以下文章

python自学笔记13:元组和字典的操作

Python面试必考重点之列表,元组和字典第九关——列表排序的方法/列表的sort方法和sorted函数的区别/倒序排列一个列表

python中列表的sort方法使用详解

Python 字典 列表 嵌套 复杂排序大全

python sort 排序的使用

python-10-列表元组嵌套