📜  Python – 记录列表中的最大值作为元组属性

📅  最后修改于: 2022-05-13 01:55:17.750000             🧑  作者: Mango

Python – 记录列表中的最大值作为元组属性

很多时候,在处理任何语言的容器时,我们都会遇到不同形式的元组列表,元组本身有时可能比本机数据类型更多,并且可以将列表作为它们的属性。本文将列表的最大值作为元组属性进行讨论。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + max()
这个特殊问题可以使用列表推导结合 max函数来解决,其中我们使用 max函数来查找列表的最大值作为元组属性,并使用列表推导来迭代列表。

# Python3 code to demonstrate
# Records element list Maximum
# using list comprehension + max()
  
# initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + max()
# Records element list Maximum
res = [(key, max(lst)) for key, lst in test_list]
  
# print result
print("The list tuple attribute maximum is : " + str(res))
输出 :
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
The list tuple attribute maximum is : [('key1', 5), ('key2', 4), ('key3', 9)]

方法 #2:使用 map + lambda + max()
上述问题也可以使用 map函数将逻辑扩展到整个列表来解决,max函数可以执行与上述方法类似的任务。

# Python3 code to demonstrate
# Records element list Maximum
# using map() + lambda + max()
  
# initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
  
# printing original list
print("The original list : " + str(test_list))
  
# using map() + lambda + max()
# Records element list Maximum
res = list(map(lambda x: (x[0], max(x[1])), test_list))
  
# print result
print("The list tuple attribute maximum is : " + str(res))
输出 :
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
The list tuple attribute maximum is : [('key1', 5), ('key2', 4), ('key3', 9)]