在 Python 中对元组列表进行排序

您所在的位置:网站首页 Python列表如何排序 在 Python 中对元组列表进行排序

在 Python 中对元组列表进行排序

2023-11-25 10:45| 来源: 网络整理| 查看: 265

使用 sorted() 函数的 key 参数对元组列表进行排序,例如 sorted_list = sorted(list_of_tuples, key=lambda t: t[1])。 该函数将按指定索引处的元组元素对元组列表进行排序。

list_of_tuples = [(1, 100), (2, 50), (3, 75)] # ✅ 按索引处的元素对元组列表进行排序(升序) sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) print(sorted_list) # 👉️ [(2, 50), (3, 75), (1, 100)] # ---------------------------------------------------- # ✅ 按索引处的元素以降序对元组列表进行排序 sorted_list_descending = sorted( list_of_tuples, key=lambda t: t[1], reverse=True ) # 👇️ [(1, 100), (3, 75), (2, 50)] print(sorted_list_descending)

sorted 函数接受一个迭代并从迭代中的项目返回一个新的排序列表。

该函数采用一个可选的 key 参数,可用于按不同的标准进行排序。

list_of_tuples = [(1, 100), (2, 50), (3, 75)] sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) print(sorted_list) # 👉️ [(2, 50), (3, 75), (1, 100)]

可以将 key 参数设置为确定排序标准的函数。

该示例按每个元组中的第二项(索引 1)对元组列表进行排序。

如果我们需要按降序(从大到小)对元组列表进行排序,请在调用 sorted() 函数时将 reverse 参数设置为 true。

list_of_tuples = [(1, 100), (2, 50), (3, 75)] sorted_list_descending = sorted( list_of_tuples, key=lambda t: t[1], reverse=True ) # 👇️ [(1, 100), (3, 75), (2, 50)] print(sorted_list_descending)

我们还可以使用这种方法按多个索引对元组列表进行排序。

list_of_tuples = [(1, 3, 100), (2, 3, 50), (3, 2, 75)] # ✅ sort list of tuples by second and third elements sorted_list = sorted( list_of_tuples, key=lambda t: (t[1], t[2]) ) print(sorted_list) # 👉️ [(3, 2, 75), (2, 3, 50), (1, 3, 100)]

该示例按每个元组中索引 1 和 2 处的元素对元组列表进行排序。

由于第三个元组中的第二项是最低的,所以它被移到前面。

!> 第一个和第二个元组中的第二个项目相等(都是 3),所以比较第三个项目,因为 50 小于 100,所以它排在第二位。

使用 lambda 函数的替代方法是使用 operator.itemgetter() 方法来指定我们想要排序的索引。

from operator import itemgetter list_of_tuples = [(1, 100), (2, 50), (3, 75)] sorted_list = sorted(list_of_tuples, key=itemgetter(1)) print(sorted_list) # 👉️ [(2, 50), (3, 75), (1, 100)]

operator.itemgetter 方法返回一个可调用对象,该对象在指定索引处获取项目。

例如,x = itemgetter(1) ,然后调用 x(my_tuple),返回 my_tuple[1]。

我们还可以使用此方法按多个索引进行排序。

from operator import itemgetter list_of_tuples = [(1, 3, 100), (2, 3, 50), (3, 2, 75)] # ✅ 按第二个和第三个元素对元组列表进行排序 sorted_list = sorted(list_of_tuples, key=itemgetter(1, 2)) print(sorted_list) # 👉️ [(3, 2, 75), (2, 3, 50), (1, 3, 100)]

使用 itemgetter 方法比使用 lambda 函数更快,但它也更加隐含。

或者,我们可以使用 list.sort() 方法。

使用 list.sort() 方法的 key 参数对元组列表进行适当的排序,例如 list_of_tuples.sort(key=lambda t: t[1])。 list.sort() 方法将按指定索引处的元组元素对元组列表进行排序。

list_of_tuples = [(1, 100), (2, 50), (3, 75)] list_of_tuples.sort(key=lambda t: t[1]) print(list_of_tuples) # 👉️ [(2, 50), (3, 75), (1, 100)]

list.sort 方法对列表进行就地排序,它仅使用



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3