在 Python 中对元组进行排序
要在 Python 中对元组进行排序,需要以下几个步骤
- 将元组传递给 sorted() 函数。
- 该函数将从元组中的项目返回一个新的排序列表。
- 将排序后的列表传递给 tuple() 类以将其转换为元组。
# ✅ 对包含数字的元组进行排序
my_tuple_1 = (3, 1, 2, 8, 10)
sorted_tuple_1 = tuple(sorted(my_tuple_1))
print(sorted_tuple_1) # 👉️ [1, 2, 3, 8, 10]
# ------------------
# ✅ 对包含字符串的元组进行排序
my_tuple_2 = ('d', 'b', 'c', 'a')
sorted_tuple_2 = tuple(sorted(my_tuple_2))
print(sorted_tuple_2) # 👉️ ['a', 'b', 'c', 'd']
# ------------------
# ✅ 按每个元组中的第二个元素对元组列表进行排序
my_list_of_tuples = [('a', 100), ('b', 50), ('c', 75)]
result = sorted(my_list_of_tuples, key=lambda t: t[1])
print(result) # 👉️ [('b', 50), ('c', 75), ('a', 100)]
上述代码运行结果如下
元组与列表非常相似,但实现的内置方法更少,并且是不可变的(无法更改)。
由于元组不能更改,对元组进行排序的唯一方法是创建一个具有所需项目顺序的新元组。
sorted 函数接受一个迭代并从迭代中的项目返回一个新的排序列表。
my_tuple_1 = (3, 1, 2, 8, 10)
sorted_list = sorted(my_tuple_1)
print(sorted_list) # 👉️ [1, 2, 3, 8, 10]
我们可以将列表传递给 tuple() 类以将其转换回元组。
sorted() 函数采用一个可选的键参数,可用于按不同的标准进行排序。
my_tuple_2 = ('abc', 'abcd', 'a', 'ab',)
sorted_tuple_2 = tuple(
sorted(my_tuple_2, key=lambda s: len(s))
)
print(sorted_tuple_2) # 👉️ ('a', 'ab', 'abc', 'abcd')
可以将 key 参数设置为确定排序标准的函数。
该示例按长度(升序)对元组中的项目进行排序。
sorted() 方法还接受一个可选的反向参数。
my_tuple_1 = (3, 1, 2, 8, 10)
sorted_tuple_1 = tuple(sorted(my_tuple_1, reverse=True))
print(sorted_tuple_1) # 👉️ (10, 8, 3, 2, 1)
# ------------------
my_tuple_2 = ('abc', 'abcd', 'a', 'ab',)
sorted_tuple_2 = tuple(
sorted(my_tuple_2, key=lambda s: len(s), reverse=True)
)
print(sorted_tuple_2) # 👉️ ('abcd', 'abc', 'ab', 'a')
如果 reverse 参数设置为 True,则对元素进行排序,就好像每个比较都被颠倒了一样。
我们还可以使用 key 参数对元组列表进行排序。
# ✅ 按每个元组中的第二个元素对元组列表进行排序
my_list_of_tuples = [('a', 100), ('b', 50), ('c', 75)]
result = sorted(my_list_of_tuples, key=lambda t: t[1])
print(result) # 👉️ [('b', 50), ('c', 75), ('a', 100)]
我们只是在每个要排序的元组中选择了项目。
该示例按第二项对元组列表进行排序。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。