2013-10-19 67 views
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)) 

回答

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

可能是我會做什麼,這應該爲更深層次的工作而努力兩個也