python 多文件列相加

多个文件每一个文件的一样的第一列的状况下, 第三列相加,没有的就补零
python

/tmp$ cat a
aa bb 1
dd bb 2
aa bb 3
ee xx 4

/tmp$ cat b
bb cc 1
aa bbb 2
cc dd 3
dd ee 4

/tmp$ cat c
kk mm 3
dd ee 2
aa dd 1
bb ee 5

这个通常awk折腾的多点。 python代码以下:bash

#!/usr/bin/env python

import sys
import fileinput

fDict = {}

for i in fileinput.input(sys.argv[1:]):
    tmp = i.split()
    fDict.setdefault(tmp[0], [0]*len(sys.argv[1:]))
    fDict[tmp[0]][sys.argv[1:].index(fileinput.filename())] += int(tmp[2])

for i in fDict:
    print i," ".join([ str(j) for j in fDict[i] ])

结果:ide

/tmp$ ./f.py a b c
aa 4 2 1
bb 0 1 5
ee 4 0 0
dd 2 4 2
kk 0 0 3
cc 0 3 0


以前觉得 fileinput.fileno 就是正在处理文件的index,结果是:ip

fileinput.fileno()
Return the integer “file descriptor” for the current file. When no file is 
opened (before the first line and between files), returns -1.

好吧,这下记住了。input

相关文章
相关标签/搜索