我从数据库中检索一些数据,这些数据在元组值列表中返回它,例如:[(1,),(1,),(1,),(1,),(1,),( 1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),( 1,),(1,),(1,)]
是否有一个函数可以总结元组列表中的值?例如,上面的示例应该返回18。
答案 0 :(得分:7)
>>>> 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
答案 1 :(得分:4)
>>> 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
答案 2 :(得分:0)
使用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