假设我有这个元组列表(可能是长度 n):
keysVals = [('one',10),('two',15),('three',20),('four',5)]
Run Code Online (Sandbox Code Playgroud)
然后我可以从这个列表中创建一个字典:
for k,v in keysVals:
d.setdefault(week,int())
d[k]+=v
Run Code Online (Sandbox Code Playgroud)
如何将以前的 dict 值添加到当前的值中,输出如下?:
d = {'one':10, 'two':25, 'three':45, 'four': 50}
Run Code Online (Sandbox Code Playgroud)
使用itertools.accumulate得到的运行总和:
import itertools
keysVals = [('one', 10), ('two', 15), ('three', 20), ('four', 5)]
keys, vals = zip(*keysVals)
d = dict(zip(keys, itertools.accumulate(vals)))
print(d)
# {'one': 10, 'two': 25, 'three': 45, 'four': 50}
Run Code Online (Sandbox Code Playgroud)