I have the follwing list of tuples:
[[(16,)], [(2,)], [(4,)]]
I want to sum up the numbers inside, but fail to to so.
I tried
res = sum(*zip(*resultsingle))
res = sum(map(sum, resultsingle))
but i get the error
TypeError: unsupported operand type(s) for : 'int' and 'tuple'
What am I missing?
CodePudding user response:
Maybe a nested comprehension would work:
>>> xss = [[(16,)], [(2,)], [(4,)]]
>>> sum(x for xs in xss for t in xs for x in t)
22
CodePudding user response:
Your list is a nested list. Where you have a list
containing list
s, containing tuple
.
This is a knows structure. And you can easily get each element and sum them. But let's say you have a nested list where you don't know how many lists or tuples are there or how they are nested?
In this case you'll need to flatten the list. Meaning, you get all the elements which are not list
or tuple
s and extend them into one list. For that you can use recursion:
def flatten(lst):
dt = []
if isinstance(lst, (list, tuple)):
for each in lst:
dt.extend(flatten(each))
else:
dt.extend([lst])
return dt
if __name__ == '__main__':
print(flatten([1, [1, 2], 3, [1, [1, 2]]]))
Result:
[1, 1, 2, 3, 1, 1, 2]
Now you only need to sum it:
print(sum(flatten([1, [1, 2], 3, [1, [1, 2]]])))
Result:
11