元组的元素加法相当简单:
a = (1,2,3,4)
b = (2,4,6,8)
tuple(x+y for x,y in zip(a,b))
(3,6,9,12)
但是嵌套元组的元素加法更复杂:
a = ((1,2),(3,4),(5,6))
b = ((2,4),(6,8),(10,12))
tuple(x+y for tup_a, tup_b in zip(a,b) for x,y in zip(tup_a,tup_b))
(3,6,9,12,15,18)
元组被展平。如何在保持元组结构的同时对嵌套元组执行元素加法?
这是所需的输出:
((3,6),(9,12),(15,18))