Python – 元组矩阵列求和
有时,在使用元组矩阵时,我们可能会遇到需要在元素级别对元组矩阵的每一列进行求和的问题。这类问题可以应用于数据科学领域。让我们讨论可以执行此任务的某些方式。
Input : test_list = [[(4, 5), (1, 2)], [(2, 4), (4, 6)]]
Output : [(6, 9), (5, 8)]
Input : test_list = [[(4, 5), (1, 2), (6, 7)]]
Output : [(4, 5), (1, 2), (6, 7)]
方法 #1:使用列表理解 + zip() + sum()
上述功能的组合可以用来解决这个问题。在此,我们使用 sum() 执行求和任务,并且 zip() 用于执行所有元素的逐列配对。
# Python3 code to demonstrate working of
# Tuple Matrix Columns Summation
# Using list comprehension + zip() + sum()
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
# printing original list
print("The original list is : " + str(test_list))
# Tuple Matrix Columns Summation
# Using list comprehension + zip() + sum()
res = [tuple(sum(ele) for ele in zip(*i)) for i in zip(*test_list)]
# printing result
print("Tuple matrix columns summation : " + str(res))
输出 :
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]
方法 #2:使用map() + list comprehension + zip()
上述功能的组合可以用来解决这个问题。在此,我们使用 map() 执行 sum() 的扩展任务,其余功能的执行类似于上述方法。
# Python3 code to demonstrate working of
# Tuple Matrix Columns Summation
# Using map() + list comprehension + zip()
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
# printing original list
print("The original list is : " + str(test_list))
# Tuple Matrix Columns Summation
# Using map() + list comprehension + zip()
res = [tuple(map(sum, zip(*ele))) for ele in zip(*test_list)]
# printing result
print("Tuple matrix columns summation : " + str(res))
输出 :
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]