1 回答
TA贡献2011条经验 获得超2个赞
我从您的问题中了解到的是,当您在两个文件中找到它们时,您想要对它们的数字进行求和,否则只需打印它们的原始值即可。您可以执行以下操作:
lines1 = [i.split() for i in open('tmp.txt').readlines()]
values,keys = zip(*lines1)
dict1 = dict( zip(keys,values) )
lines2 = [i.split() for i in open('tmp2.txt').readlines()]
values,keys = zip(*lines2)
dict2 = dict( zip(keys,values) )
dict3 = {}
for k1,v1 in dict1.items():
v2 = dict2.get(k1)
if v2:
dict3[k1] = str(float(v1)/float(v2))
else:
dict3[k1] = v1
for k2,v2 in dict2.items():
if not dict3.get(k2):
dict3[k2] = v2
out = open('output.txt','w')
out.writelines(['%s\t%s\n' %\
(k[0],dict3[k[0]]) for k in sorted(dict3.items(), key=lambda x:x[1])])
out.close()
添加回答
举报