【发布时间】:2026-01-08 12:50:01
【问题描述】:
我有一个列表: 结果=[[0.0, 12.053600000000001], [0.01, 14.2272], [0.02, 15.314000000000002], [0.04, 18.5744], [0.05, -18.772000000000002]], [0.67, -1.54]
我有一个 in.txt 文件,其中包含以下值:
NPTH 6
THTIM
0.0 0.00 0.001 -1.22
0.01 0.123 0.550 -1.44
0.02 0.22 0.440 -1.55
0.04 0.456 0.220 -1.88
0.05 0.788 0.005 1.9
0.67 0.23 0.340 0.2
NPPD 4
1.0 5.0 8.0
1.0 4.0 2.0
2.0 5.0 2.0
4.0 5.0 2.0
THTIM 5
2.0 1.0
1.0 2.0
1.0 1.0
我需要用结果列表中每个列表中的第二个参数替换 THTIM 之后的第二列,即 in.txt 文件中的字符串 0.00,0.123,0.22,0.456,0.788,0.23 需要替换为 12.053600000000001,14.2272,15.314000000000002,分别为 18.5744、-18.772000000000002、-1.54。 即我需要我的输出为
NPTH 6
THTIM
0.00 12.053600000000001 0.001 -1.22
0.01 14.2272 0.550 -1.44
0.02 15.314000000000002 0.440 -1.55
0.04 18.5744 0.220 -1.88
0.05 -18.772000000000002 0.005 1.9
0.67 -1.54 0.340 0.2
NPPD 4
1.0 5.0 8.0
1.0 4.0 2.0
2.0 5.0 2.0
4.0 5.0 2.0
THTIM 5
2.0 1.0
1.0 2.0
1.0 1.0
我试过的是:
f3=open("in.txt" ,'r')
import re
result=[[0.0, 12.053600000000001], [0.01, 14.2272], [0.02,15.314000000000002], [0.04, 18.5744], [0.05, -18.772000000000002], [0.67, -1.54]]
o2=open("out.txt" ,'w')
thtm2Cnt=0
thtm2Flag=0
for ot in f3.readlines():
ou=ot
print(ot)
if re.match('NPTH',ou):
o2.write(ou)
strplt =ou.split()
cnt=int(strplt[1])
elif re.match('THTIM',ou):
thtm2Flag=1
o2.write(ou)
elif thtm2Flag==1:
if thtm2Cnt<=cnt-1:
strplt=ou.split()
ou = strplt[0] + "\t" + "\t" + strplt[2] + "\t" + strplt[3] + " \n "
o2.write(ou)
thtm2Cnt+=1
elif thtm2Cnt==cnt:
thtm2Cnt=0
thtm2Flag=0
o2.write(ou)
else:
o2.write(ou)
请提供代码以实现此目的。 (编辑:导入 re 并声明变量)
【问题讨论】:
标签: python string file arraylist replace