用最大元素对元组进行排序的 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”函数给出最高值。

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

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

  • 它以相反的顺序显示。

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

猜你喜欢