從 Python 元組列表中獲取第 N 列的最大值


當需要從元組列表中獲取第“N”列的最大值時,可以使用列表解析和“max”方法來完成。

列表解析是一種在列表中進行迭代並對其執行操作的速記方法。“max”方法返回可迭代物件中值的最大值。

列表可用於儲存異構值(即任何資料型別的資料,如整數、浮點數、字串等)。

元組列表基本上包含一個列表中的元組。

以下是這方面的演示例子 −

示例

即時演示

my_list = [( 67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)]

print ("The list is : " )
print(my_list)
N = 2
print("The value of 'N' has been initialized")

my_result = max([sub[N] for sub in my_list])

print("The maximum of Nth column in the list of tuples is : " )
print(my_result)

輸出

The list is :
[(67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)]
The value of 'N' has been initialized
The maximum of Nth column in the list of tuples is :
78

說明

  • 定義了一個元組列表,並在控制檯上顯示。
  • 初始化“N”的值。
  • 使用列表解析遍歷元組列表,並使用“max”方法從元組列表中獲取最大值。
  • 將此操作分配給一個變數。
  • 該變數是顯示在控制檯上的輸出。

更新日期: 11-Mar-2021

198 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.