Adding values in a tuple that is in a list in python
I retrieve some data from a database which returns it i开发者_C百科n a list of tuple values such as this: [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
Is there a function that can sum up the values in the list of tuples? For example, the above sample should return 18.
>>>> l=[(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> sum(map(sum,l))
18
>>> l[0]=(1,2,3,)
>>> l
[(1, 2, 3), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> sum(map(sum,l))
23
>>> l = [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> s = sum(i[0] for i in l)
>>> print s
18
Just some fun with itertools, not very readable. Works only if you consider 1st element in tuple.
>>> import itertools
>>> l = [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> sum(*itertools.izip(*l))
18
精彩评论