我正在阅读以下格式的文件:
0.012281001 00:1c:c4:c2:1f:fe 1 30
0.012285001 00:1c:c4:c2:1f:fe 3 40
0.012288001 00:1c:c4:c2:1f:fe 2 50
0.012292001 00:1c:c4:c2:1f:fe 4 60
0.012295001 24:1c:c4:c2:2f:ce 5 70
我打算将第2列实体作为键,将第3列和第4列作为单独的值。对于我遇到的每一行,对于该特定键,它们各自的值必须相加(值1和值2应分别为该键聚合)。在上面提到的例子中,我需要得到如下输出:
'00:1c:c4:c2:1f:fe': 10 : 180, '24:1c:c4:c2:2f:ce': 5 : 70
我为简单的1键1值编写的程序如下:
#!/usr/bin/python
import collections
result = collections.defaultdict(int)
clienthash = dict()
with open("luawrite", "r") as f:
for line in f:
hashes = line.split()
ckey = hashes[1]
val1 = float(hashes[2])
result[ckey] += val1
print result
如何将此值扩展为2个值,如何将其打印为上述输出。我没有得到任何想法。请帮忙!顺便说一下,我正在使用python2.6
答案 0 :(得分:2)
您可以使用元组作为存储值将所有值存储在单个字典中:
with open("luawrite", "r") as f:
for line in f:
hashes = line.split()
ckey = hashes[1]
val1 = int(hashes[2])
val2 = int(hashes[3])
a,b = result[ckey]
result[ckey] = (a+val1, b+val2)
print result