📜  Python|元组的列求和

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

Python|元组的列求和

有时,我们遇到一个问题,我们处理复杂类型的矩阵列求和,其中给定一个元组,我们需要对其相似元素执行求和。这在机器学习领域有很好的应用。让我们讨论一些可以做到这一点的方法。

方法 #1:使用zip() + 列表理解
这个问题可以使用可以执行列求和逻辑的列表推导来解决,并且 zip函数用于绑定元素作为结果以及在垂直求和时。

# Python3 code to demonstrate
# column summation of list of tuple
# using list comprehension + zip()
  
# initializing list 
test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + zip()
# columnn summation of list of tuple
res = [tuple(sum(j) for j in zip(*i))
            for i in zip(*test_list)]
  
# print result
print("The summation of columns of tuple list : " + str(res))
输出 :
The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]]
The summation of columns of tuple list : [(4, 11), (3, 12), (15, 7)]

方法 #2:使用zip() + map()
绑定列元素的任务也可以使用 map函数执行,而 zip函数执行绑定求和元组的任务。两种逻辑都受列表理解的约束。

# Python3 code to demonstrate
# column summation of list of tuple
# using zip() + map()
  
# initializing list 
test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
  
# printing original list
print("The original list : " + str(test_list))
  
# using zip() + map()
# columnn summation of list of tuple
res = [tuple(map(sum, zip(*i))) 
      for i in zip(*test_list)]
  
# print result
print("The summation of columns of tuple list : " + str(res))
输出 :
The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]]
The summation of columns of tuple list : [(4, 11), (3, 12), (15, 7)]