我有一个文件“input.txt”,其中包含6列
520743 ID:1 407585 16630998 70843 174935
540743 ID:1 418010 17275747 70843 179499
560744 ID:1 429340 17919579 70905 183799
580744 ID:1 439450 18564636 70905 188148
20595 ID:2 29487 625836 11282 10382
40596 ID:2 45984 1264642 14266 20974
21258 ID:3 46215 609159 20895 16586
41259 ID:3 63166 1247485 24201 24052
61257 ID:3 72732 1893258 24201 28660
如果tge ID
相同,我想从每个列值中减去前一行列值。例如Line2_cloumn3 - line1_column3: 418010 - 407585 = 10425
并写入另一个文件:
20000 ID:1 10425 644749 0 4564
我怎么能在python中做到这一点?
答案 0 :(得分:0)
with open('input.txt') as inf, open('out.txt', 'w') as outf:
prev = next(inf)
string = prev.split()[1]
abc=int(string.split(":",1)[1])
for line in inf:
string = prev.split()[1]
abc=int(string.split(":",1)[1])
cstring = line.split()[1]
cabc=int(cstring.split(":",1)[1])
if abc==cabc:
value=[]
pval1=int(prev.split()[2])
cval1=int(line.split()[2])
val1=cval1-pval1
value.append(val1)
pval2=int(prev.split()[3])
cval2=int(line.split()[3])
val2=cval2-pval2
value.append(val2)
pval3=int(prev.split()[4])
cval3=int(line.split()[4])
val3=cval3-pval3
value.append(val3)
pval4=int(prev.split()[5])
cval4=int(line.split()[5])
val4=cval4-pval4
value.append(val4)
prev=line
我写了这段代码,它有效。我怎样才能改善这个?