在 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)]
我们只是在每个要排序的元组中选择了项目。
该示例按第二项对元组列表进行排序。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。