Python 程序按元组中的最大元素排序


如果需要按元组中最大元素对元组进行排序,则会定义一种使用“max”方法来返回最高元素的方法。

接下来,可以使用“sort”方法按先前定义的函数对列表进行排序。

以下是相同演示:

示例

 实时演示

def get_max_value(my_val):
   return max(my_val)

my_list = [(4, 6, 8, 1), (13, 21, 42, 56), (7, 1, 9,0), (1, 2)]

print(“The list is : “)
print(my_list)
my_list.sort(key = get_max_value, reverse = True)

print(“The sorted tuples are : “)
print(my_list)

输出

The list is :
[(4, 6, 8, 1), (13, 21, 42, 56), (7, 1, 9, 0), (1, 2)]
The sorted tuples are :
[(13, 21, 42, 56), (7, 1, 9, 0), (4, 6, 8, 1), (1, 2)]

解释

  • 定义了一个名为“get_max_value”的方法,该方法使用‘max’函数来给出最高值。

  • 定义元组列表,并在控制台上显示元素。

  • 根据先前定义函数的键对列表进行排序。

  • 按倒序显示。

  • 这是在控制台上显示的输出。

更新于: 15-Apr-2021

243 次浏览

开启您的职业生涯

通过完成课程获得认证

开始使用
广告
© . All rights reserved.