如何使用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
相关产品推荐
相关产品推荐

