2016-03-07 58 views

回答

3

不使用循環中,您可以使用zip()功能:

>>> sum(list(zip(*a))[1]) 
15 

:如果您在使用python 2.X因爲zip返回一個列表,而不是你所不懂的迭代器在zip函數上需要使用list()

3

悟:

a = [[1,2,3],[4,5,6],[7,8,9]] 
print(sum(sublist[1] for sublist in a)) 

將導致

15 
2

使用減少,所以你不要在內存中創建中間對象:

>>>from functools import reduce 
>>>reduce(lambda x, y: x + y[1], a, 0) 
>>>15 
1

所有其他的答案是完全正常的,但這裏有第四種方式:

>>> import operator 
>>> sum(map(operator.itemgetter(2), a)) 
15 
相關問題