在字典上循环(先前值)python
我有一个字典,这个字典把每个字符和一个概率值关联起来。
d = {'a': 0.2, 'b': 0.3, 'c': 0.4, 'd':0.1}
现在我想给每个字符关联上它的频率分布中的最低值。也就是说,每个字符都应该和之前所有字符的概率值相加在一起。我知道字典里的内容是没有顺序的,但我希望能得到类似这样的结果:
ddist = {'a': 0, 'b': 0.2, 'c': 0.5, 'd': 0.9}
我试着用循环来实现,但我找不到获取之前值的方法……
有没有什么好主意呢?
2 个回答
1
因为字典是无序的,所以你需要自己定义键的顺序,或者一开始就使用collections.OrderedDict
。
>>> def accumulate(seq):
total = 0
for item in seq:
yield total
total += item
...
>>> keys = ['a', 'b', 'c', 'd'] #For your dict, this is sorted(d)
>>> dict(zip(keys, accumulate(d[k] for k in keys)))
{'a': 0, 'c': 0.5, 'b': 0.2, 'd': 0.9}
#or
>>> from collections import OrderedDict
>>> OrderedDict(zip(keys, accumulate(d[k] for k in keys)))
OrderedDict([('a', 0), ('b', 0.2), ('c', 0.5), ('d', 0.9)])
3
你可以简单地遍历一个排序过的键的版本:
d = {'a': 0.2, 'b': 0.3, 'c': 0.4, 'd':0.1}
ddist = {}
t = 0
for key in sorted(d):
ddist[key] = t
t += d[key]