2

元组的元素加法相当简单:

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))
4

2 回答 2

1

嵌套生成器表达式:

tuple(tuple(x + y for x, y in zip(tup_a, tup_b)) for tup_a, tup_b in zip(a, b))

演示:

>>> a = ((1,2),(3,4),(5,6))
>>> b = ((2,4),(6,8),(10,12))
>>> tuple(tuple(x + y for x, y in zip(tup_a, tup_b)) for tup_a, tup_b in zip(a, b))
((3, 6), (9, 12), (15, 18))
于 2013-10-19T19:57:57.797 回答
1
def xsum(a,b):
    if isinstance(a,(list,tuple)) and isinstance(b,(list,tuple)):
       return [xsum(x,y) for x,y in zip(a,b)]
    return a+b

a = ((1,2),(3,4),(5,6))
b = ((2,4),(6,8),(10,12))
print [xsum(x,y) for x,y in zip(a,b)]

可能是我会做的,这应该适用于更多层次的深度,而不仅仅是两个

于 2013-10-19T19:59:30.827 回答