1

我有以下(空格分隔)输入:

2012-10-05 PETER 6  
2012-10-05 PETER 4  
2012-10-06 PETER 60
2012-10-06 TOM 10  
2012-10-08 SOMNATH 80 

我想实现以下以管道分隔的输出:(其中列是 [DATE AND NAME, NUM ENTRIES, SUM OF LAST COL])

2012-10-05 PETER|2|10  
2012-10-06 PETER|1|60  
2012-10-06 TOM|1|10  
2012-10-08 SOMNATH|1|80  

到目前为止,这是我的代码:

s = open("output.txt","r")
fn=s.readlines()
d = {}
for line in fn:
 parts = line.split()
 if parts[0] in d:
   d[parts[0]][1] += int(parts[2])
   d[parts[0]][2] += 1
 else:
d[parts[0]] = [parts[1], int(parts[2]), 1]
for date in sorted(d):
   print "%s %s|%d|%d" % (date, d[date][0], d[date][2], d[date][1])

我得到的输出为:

2012-10-06 PETER|2|70

代替

2012-10-06 PETER|1|60

并且TOM没有显示在列表中。

我需要做什么来更正我的代码?

4

2 回答 2

2
d = collections.defaultdict(list)
with open('output.txt', 'r') as f:
    for line in f:
        date, name, val = line.split()
        d[date, name].append(int(val))

for (date, name), vals in sorted(d.items()):
    print '%s %s|%d|%d' % (date, name, len(vals), sum(vals))
于 2012-10-06T09:12:49.800 回答
0

<3itertools

import itertools
with open('output.txt', 'r') as f:
    splitlines = (line.split() for line in f if line.strip())
    for (date, name), bits in itertools.groupby(splitlines, key=lambda bits: bits[:2]):
        total = 0
        count = 0
        for _, _, val in bits:
            total += int(val)
            count += 1
        print '%s %s|%d|%d' % (date, name, count, total)

如果您不想使用groupby(它不可用,或者您的输入数据不能保证被排序),这是一个传统的解决方案(实际上只是您代码的固定版本):

d = {}
with open('output.txt', 'r') as f:
    for line in f:
        date, name, val = line.split()
        key = (date, name)
        if key not in d:
            d[key] = [0, 0]
        d[key][0] += int(val)
        d[key][1] += 1

for key in sorted(d):
    date, name = key
    total, count = d[key]
    print '%s %s|%d|%d' % (date, name, count, total)

请注意,我们使用(date, name)as 键而不是仅使用date.

于 2012-10-06T08:51:28.720 回答