我有一个像这样的列表
GroupID,Number
yellow,1
yellow,2
tan,0
blue,1
black,2
black,3
我想要的是这个
GroupID,Number
yellow,3
tan, 0
blue,1
black,5
所以我想添加与每个groupID相关联的数字。
这是我得到的,但结果陈述有困难:
from collections import defaultdict
d = defaultdict(list)
f = open("metal_modules.csv","r")
sheet = f.readlines()
#print sheet
for line in sheet[1:]:
#print line
spl = line.strip().split(",")
#print spl[1]
name = spl[0]
d[name].append(spl[1])
outfile = open("out.txt","w")
result = ""
for v in d.values():
result = #here I need to sum the number in column two for each key in the dictionary#
#print result
outfile.write(result)
f.close()
outfile.close()
答案 0 :(得分:2)
保持简单
result = ""
for group in d:
result += "%s, %s\n" % (group, sum(n for n in d[group]))
答案 1 :(得分:1)
如果订单对您来说不是一个重要问题,您可以尝试以下方法。
from collections import defaultdict
with open('infile') as f:
d = defaultdict(list)
h = f.readline()
m = f.readlines()
for i in m:
s = i.rstrip().split(',')
d[s[0]].append(s[1])
with open('outfile', 'w') as w:
w.write(h)
for i in d.items():
w.write(i[0]+","+str(sum(map(int,i[1])))+"\n")
答案 2 :(得分:0)
看看以下内容:
with open("metal_modules.csv","r") as f:
sheet = f.readlines()
counter = {}
for line in sheet[1:]:
k,v = line.split(",")
if k in counter:
counter[k] += int(v)
else:
counter[k] = int(v)
with open("out.txt","w") as outfile:
result = "GroupID,Number\n"
for item in counter:
result += "%s,%s\n" % (item,counter[item])
outfile.write(result.strip())