在Python中找出每個子列表中的最大值


我們給定一個列表的列表。在內部列表或子列表中,我們需要找出每個列表中的最大值。

使用max和in

我們設計了一個帶有in條件的for迴圈,並應用max函式來獲取每個子列表中的最大值。

示例

 線上演示

Alist = [[10, 13, 454, 66, 44], [10, 8, 7, 23]]
# Given list
print("The given list:\n ",Alist)
# Use Max
res = [max(elem) for elem in Alist]
# Printing max
print("Maximum values from each element in the list:\n ",res)

輸出

執行以上程式碼可得到以下結果 −

The given list:
[[10, 13, 454, 66, 44], [10, 8, 7, 23]]
Maximum values from each element in the list:
[454, 23]

使用map和max

在迭代子列表時,我們繼續使用map應用max函式。

示例

 線上演示

Alist = [[10, 13, 454, 66, 44], [10, 8, 7, 23]]
# Given list
print("The given list:\n ",Alist)
# Use Max
res =list(map(max, Alist))
# Printing max
print("Maximum values from each element in the list:\n ",res)

輸出

執行以上程式碼可得到以下結果 −

The given list:
[[10, 13, 454, 66, 44], [10, 8, 7, 23]]
Maximum values from each element in the list:
[454, 23]

更新於:2020年6月4日

305次瀏覽

開啟你的 職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.