Python|列表的总和作为元组属性
很多时候,在处理任何语言的容器时,我们都会遇到不同形式的元组列表,元组本身有时可能比本机数据类型更多,并且可以将列表作为它们的属性。这篇文章讲的是列表作为元组属性的求和。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + sum()
这个特殊问题可以使用列表推导结合 sum函数来解决,其中我们使用 sum函数将列表的总和作为元组属性和列表推导来迭代列表。
# Python3 code to demonstrate
# Summation of list as tuple attribute
# using list comprehension + sum()
# 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 + sum()
# Summation of list as tuple attribute
res = [(key, sum(lst)) for key, lst in test_list]
# print result
print("The list tuple attribute summation is : " + str(res))
输出 :
The original list : [(‘key1’, [3, 4, 5]), (‘key2’, [1, 4, 2]), (‘key3’, [9, 3])]
The list tuple attribute summation is : [(‘key1’, 12), (‘key2’, 7), (‘key3’, 12)]
方法 #2:使用 map + lambda + sum()
上述问题也可以使用 map函数将逻辑扩展到整个列表来解决,sum函数可以执行与上述方法类似的任务。
# Python3 code to demonstrate
# Summation of list as tuple attribute
# using map() + lambda + sum()
# 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 + sum()
# Summation of list as tuple attribute
res = list(map(lambda x: (x[0], sum(x[1])), test_list))
# print result
print("The list tuple attribute summation is : " + str(res))
输出 :
The original list : [(‘key1’, [3, 4, 5]), (‘key2’, [1, 4, 2]), (‘key3’, [9, 3])]
The list tuple attribute summation is : [(‘key1’, 12), (‘key2’, 7), (‘key3’, 12)]