在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.