要做到這一點,最簡單的方法是用the sum()
builtin和generator expression:
>>>items = [[datetime.datetime(2000, 12, 10, 0, 0), 0.0011], [datetime.datetime(2000, 12, 11, 0, 0), 0.0013 ], [datetime.datetime(2000, 12, 12, 0, 0), 0.0014]]
>>>sum(item[1] for item in items)
0.0038000000000000004
編輯:
如果你想打印出求和的每一個階段的結果,要使用functools.reduce()
(在2.x中是the reduce
builtin)。
from functools import reduce
import datetime
items = [[datetime.datetime(2000, 12, 10, 0, 0), 0.0011], [datetime.datetime(2000, 12, 11, 0, 0), 0.0013 ], [datetime.datetime(2000, 12, 12, 0, 0), 0.0014]]
def add_printing_result(a, b):
total = a+b
print(total)
return total
reduce(add_printing_result, (item[1] for item in items))
這給了我們:
0.0024000000000000002
0.0038000000000000004
謝謝你,但是這會給我總的(有趣的,因爲我正在使用減少功能很長的路要走)。我怎樣才能把它打印出來而不是總數呢? – 2012-04-27 01:26:18
@Julz編輯提供該解決方案。 – 2012-04-27 02:00:28