我的文件有以下几种值:
123 9
111 5
12 1
123 4
12 4
109 5
12 4
35 7
111 4
124 6
现在我们必须生成一个输出,如:
123 13
111 9
12 5
109 5
35 7
124 6
即。如果value
在写入输出期间出现两次,我们只会写value
一次,并总结count
的{{1}}。
我认为可以使用value
函数来完成,但我很困惑如何总结这个值
请帮忙。
答案 0 :(得分:4)
如果您不关心元素的顺序,那么您可以使用Karls方法。
否则使用已排序的词典:
import collections
data = [(123, 9), (111, 5), (12, 1), (123, 4), (12, 4),
(109, 5), (12, 4), (35, 7), (111, 4), (124, 6)]
order = collections.OrderedDict()
for value, count in data:
order[value] = order.setdefault(value, 0) + count
它类似于使用defaultdict,你可以在构造上传递一个函数,返回字典中找不到的键的默认值:
import collections
default = collections.defaultdict(int)
for value, count in data:
default[value] += count
但在这种情况下,也不保留元素的顺序。
答案 1 :(得分:2)
使用collections.Counter
。像
counter = collections.Counter()
for a, b in data: counter.update({a: b})
答案 2 :(得分:-2)
使用ordereddict
之类的
mydict = ordereddict()
try:
mydict[val] = mydict[val] + additional_val
except KeyError:
mydict[val] = additional_val