在 Python 中查找给定嵌套列表中具有最大值的子列表

pythonserver side programmingprogramming更新于 2026/1/22 19:24:17

列表可以包含其他列表作为其元素。在本文中,我们将找到给定列表中具有最大值的子列表。

使用 max 和 lambda

max 和 Lambda 函数可以一起使用来给出具有最大值的子列表。

示例

listA = [['Mon', 90], ['Tue', 32], ['Wed', 120]]
# 使用 lambda
res = max(listA, key=lambda x: x[1])
# 打印输出
print("给定列表:\n", listA)
print("List with maximum value:\n ", res)

输出

运行上述代码得到以下结果 −

给定列表:
[['Mon', 90], ['Tue', 32], ['Wed', 120]]
List with maximum value:
['Wed', 120]

使用 itergetter

我们从索引位置 1 使用 itemgetter,并应用 max 函数来获取具有最大值的子列表。

示例

import operator
listA = [['Mon', 90], ['Tue', 32], ['Wed', 120]]
# 使用 itemgetter
res = max(listA, key = operator.itemgetter(1))
# 打印输出
print("给定列表:\n", listA)
print("List with maximum value:\n ", res)

输出

运行上述代码得到以下结果 −

给定列表:
[['Mon', 90], ['Tue', 32], ['Wed', 120]]
List with maximum value:
['Wed', 120]

相关文章


有用资源