我从数据库中检索到一些数据,它以元组值的列表形式返回,例如:[(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
是否有一个函数可以对元组列表中的值进行求和?例如,上面的示例应该返回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
使用itertools玩个乐呵,不太易读。仅在考虑元组中的第一个元素时有效。
>>> 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
(1,)
吗?你可以直接使用len
:) - John La Rooy