Python程序:按字母顺序排序元组列表


当需要按字母顺序排序元组列表时,可以使用`sort`方法。使用此方法时,原始元组的内容会发生更改,因为执行的是就地排序。

`sort`函数默认按升序排序值。如果排序顺序指定为降序,则按降序排序。

列表可以用来存储异构值(即任何数据类型的数据,例如整数、浮点数、字符串等等)。

元组列表基本上包含在一个列表中封闭的元组。

下面是一个演示:

示例

在线演示

def sort_tuple_vals(my_tup):  
   my_tup.sort(key = lambda x: x[0])
   return my_tup
my_tup = [("Hey", 18), ("Jane", 33), ("Will", 56),("Nysa", 35), ("May", "Pink")]
     
print("The tuple is ")
print(my_tup)
print("After sorting the tuple alphabetically, it becomes : ")
print(sort_tuple_vals(my_tup))

输出

The tuple is
[('Hey', 18), ('Jane', 33), ('Will', 56), ('Nysa', 35), ('May', 'Pink')]
After sorting the tuple alphabetically, it becomes :
[('Hey', 18), ('Jane', 33), ('May', 'Pink'), ('Nysa', 35), ('Will', 56)]

解释

  • 定义了一个名为`sort_tuple_vals`的函数,它以元组作为参数。
  • 它使用`sort`方法和lambda函数对元组中的元素进行排序。
  • 调用函数时返回此结果。
  • 现在定义了元组,并通过将此元组作为参数来调用函数。
  • 输出显示在控制台上。

更新于:2021年3月11日

2K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.