如何在Python中修改表?

时间:2013-04-15 05:58:22

标签: python text io

我在.txt文件中有一个表格,如下所示:

GROUP TYPE FRACTION
1     A    0.1
1     B    0.6
1     C    0.3
2     A    0.7
2     C    0.3

如何重新排列记录以使表格如下所示并写入Python中的另一个txt文件:

GROUP TYPE_A TYPE_B TYPE_C
1     0.1    0.6    0.3
2     0.7    0.0    0.3

谢谢!

1 个答案:

答案 0 :(得分:0)

from collections import defaultdict
d = defaultdict(dict)

with open('test.txt') as f:
    next(f, None) # skip header

    for line in f:
        group, type_, fraction = line.split()
        d[group][type_] = fraction

types = sorted(set(k for g in d.values() for k in g))

print 'GROUP ' + ''.join('{:<7}'.format('TYPE_' + t) for t in types)
for i, g in sorted(d.items()):
    print '{0:<6}'.format(i) + ''.join('{:<7}'.format(g.get(k, 0.0)) 
                                       for k in types)

输出:

GROUP TYPE_A TYPE_B TYPE_C 
1     0.1    0.6    0.3    
2     0.7    0.0    0.3