使用 Python 程序按每个元组的最后一个元素升序排序元组列表


当需要根据每个元组的最后一个元素按升序对元组列表进行排序时,会定义一个方法,该方法迭代元组并执行简单的交换以实现相同目的。

以下是相同内容的演示 -

示例

 在线演示

def sort_tuple(my_tup):

   my_len = len(my_tup)
   for i in range(0, my_len):

      for j in range(0, my_len-i-1):
         if (my_tup[j][-1] > my_tup[j + 1][-1]):
            temp = my_tup[j]
            my_tup[j]= my_tup[j + 1]
            my_tup[j + 1]= temp
   return my_tup

my_tuple =[(1, 92), (34, 25), (67, 89)]
print("The tuple is :")
print(my_tuple)

print("The sorted list of tuples are : ")
print(sort_tuple(my_tuple))

输出

The tuple is :
[(1, 92), (34, 25), (67, 89)]
The sorted list of tuples are :
[(34, 25), (67, 89), (1, 92)]

解释

  • 定义了一个名为“sort_tuple”的方法,它以元组列表作为参数。

  • 它遍历列表,并检查元组列表中每个元组的最后一个元素是否大于或小于。

  • 使用简单的交换将它们放在正确的位置。

  • 元组列表作为输出返回。

  • 在方法外部,定义了一个元组列表,并在控制台上显示。

  • 通过传递此元组列表来调用该方法。

  • 输出显示在控制台上。

更新于: 2021年4月19日

719 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.