python built in reducebykey -
is there built-in reducebykey functionality in python? if not, how can imitate functionality?
for example, if i'm doing simple word count:
>>> x=[('a', 1), ('a', 1), ('b', 1), ('c', 1)] >>> reduce(lambda a,b:a+b, x) ('a', 1, 'a', 1, 'b', 1, 'c', 1)
what wanted have return [('a',2), ('b',1), ('c',1)]. reduce() function ended iterating through tuples together, , didn't combine keys. way around this?
you can use ordereddict. preserve order also.
from collections import ordereddict result = ordereddict() item in x: result[item[0]] = result.get(item[0], 0) + item[1] result [('a', 2), ('b', 1), ('c', 1)]
here, iterating on dictionary. key item[0]
in result
ordereddict. if found, add item[1]
1 in our case value present there. else, take default value 0 , add item[1]
(this happen when element encountered first time).
Comments
Post a Comment