-
www说
您可以使用 ,并得到结果:mapsumsumsum(map(sum, t))# 6或者,如果您更喜欢使用 for 循环:res = 0for i in t: res += sum(i)print(res)# 6
-
暮色呼如
您可以循环元组来求和所有内容。此代码很长,但总和可以为 。tupletuplet = ((1, 1), (1, 1), (1, 1))# Tuple in tuple:t = ((1, 1, (1, 1, (1, 1))))def getsum(var, current = 0): result = current if type(var) == tuple: for i in range(len(var)): x = var[i] result = getsum(x, result) else: result += var return resultprint(getsum(t))
-
Helenr
你可以使用简单的迭代(在python3.8中工作,我假设它也适用于旧版本)。t = ((1, 1), (1, 1), (1, 1)) sum_tuples = 0for a,b in t: sum_tuples += a # First element sum_tuples += b # Second Elementprint(sum_tuples) # prints 6
-
扬帆大鱼
你可以使用 itertools.chain>>> import itertools>>> t = ((1, 1), (1, 1), (1, 1)) >>> sum(itertools.chain.from_iterable(t))6