多個文件每一個文件的一樣的第一列的狀況下, 第三列相加,沒有的就補零
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