python - how to accumulate the value according to the key in a defaultdict -
if have defaultdict(list)
d =defaultdict(list) such 1: 0 1:0.2 1: 0.3 2: 0.2 2: 0.4 2: 0.1
...... how transform similar defaultdict(list) values accumulation of values of 1st dict same key, never bigger 1
1: 0 1: 0.2 1: 0.5 2: 0.2 2: 0.6 2: 0.7 .....
i have next code far, not quite right :-(
d2 = defaultdict(list) k in d.iterkeys() v +=d(k) d2[k]. append(v)
the original post little confusing: examples multimap rather dict of lists.
i assume have defaultdict lists of numbers , you'd create new defaultdict contains cumulative sum of values in each list. seek this:
d2 = defaultdict(list) k, v in d.iteritems(): sum = 0.0 v2 = [] x in v: sum += x v2.append(sum) d2[k] = v2
note new defaultdict won't auto-compute cumulative sums add together new values.
if have library numpy installed, can utilize numpy.cumsum
instead of using python loop compute cumulative sum.
it's not clear me mean "never bigger 1." want ignore elements after cumulative sum reaches 1? want ignore individual values greater 1, maintain accumulating smaller ones, if sum grows beyond 1? want have same number of elements in each output list, cap element values @ 1?
python map iterator key defaultdict
No comments:
Post a Comment