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.