You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用for循环和max函数提取多组列表的最大值并生成新列表

解决方案

生成Output 1的代码

通过zip()函数将persons和values中的元素一一配对,用for循环遍历每一组数据,结合max()函数提取对应元组的最大值,最后组装成目标元组列表:

persons = ['John', 'James', 'Robert']
values = [
    (101, 97, 79),
    (67, 85, 103),
    (48, 201, 105),
]

output1 = []
for name, val_tuple in zip(persons, values):
    max_val = max(val_tuple)
    output1.append( (name, max_val) )

print(output1)  # 输出: [('John', 101), ('James', 103), ('Robert', 201)]

生成Output 2的代码

直接遍历values中的每个元组,用max()函数提取最大值并添加到结果列表即可:

output2 = []
for val_tuple in values:
    output2.append( max(val_tuple) )

print(output2)  # 输出: [101, 103, 201]

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 19:00:31