2013-04-15 31 views
-3

我有這樣的.txt文件的表:如何在Python中修改表?

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 

謝謝!

回答

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  
+0

@downvoter我請你拿回來downvote除非你能向我,爲什麼你認爲這是不是一個有用的答案解釋。 – jamylak