python - Python从许多文件中添加数字而不使用太多内存
问题描述
我编写了一个 python 脚本,它运行良好(见下文)。代码从不同的输入文件中读取行并尝试进行一些计算。输入文件如下所示:
Timestep 1000
Y TESFG
1.5
1.3
1.2
1.8
Timestep 1001
Y TESFG 1
1.0
1.0
1.0
1.2
Timestep 1002
Y TESFG 1
1.0
1.0
1.0
1.2
等等....
主输出文件(变量 sed)的格式相同,如下所示:
Timestep 1000
Y TESFG
1.0
1.0
1.0
1.0
Timestep 1001
Y TESFG 1
2.0
2.0
2.0
2.0
Timestep 1002
Y TESFG 1
1.0
1.0
1.0
1.2
我想在一个输出文件中对所有时间步长的变量“sed”求和。我使用 append 创建一个新列表并计算每一行的加法,但我的文件太大了,使用 append 需要太多时间。
您能否提供一些提示,如何将时间步下的每个数字彼此相加,以使结果如下所示:
Timestep all
Y TESFG 1
4.0
4.0
4.0
4.2
with open('a.dat', 'r') as v1, open('b.dat', 'r') as d2, open('st.dat','r') as st3 ,
open('v.dat','r') as A, open('sch.txt','w') as outfile, open('pro.txt','w') as outfile2,
open('Sed.txt','w') as outfile3, open('Sed.txt','w') as outfile4:
for line1,line2,line3,line4 in zip(v1,d2,st3,A):
try:
line1 = line1.strip()
line2 = line2.strip()
line3 = line3.strip()
line4 = line4.strip()
column1 = line1.split()
column2 = line2.split()
column3 = line3.split()
column4 = line4.split()
v1 = float(column1[0])
d2 = float(column2[0])
if d2==0.00:
d2=0.01
st3 = float(column3[0])
if st3 > 100:
st3=100
Sch = 1000*9.807*d2**(-1/3)*(v1)**2/(st3)**2
p=1-(Sch/Sch_crit)
if abs(p) > 1.0:
p=1.0
w_s=dm**2*9.807*(rou_s-rou_w)/(18*nou*rou_w)
sed_rate=abs(p)*w_s*K
area = float(column4[0])
sed = sed_rate * 3600 *area
print("{:.6f}".format(sediment), file=outfile4)
print("{:.2f}".format(Schub), file=outfile)
print("{:.2f}".format(abs(p)), file=outfile2)
print("{:.6f}".format(sediment_rate), file=outfile3)
#outfile.write("%.2f\t %.2f\n" % (vx,vy))
except ValueError:
print(line2, file=outfile4)
print(line2, file=outfile)
print(line2, file=outfile2)
print(line2, file=outfile3)
*************************编辑***********************
摘要:我有这个输入文件
Timestep 1000
Y TESFG 1
1.0
1.0
1.0
1.0
Timestep 1001
Y TESFG 1
2.0
2.0
2.0
2.0
Timestep 1002
Y TESFG 1
1.0
1.0
1.0
1.2
我想得到这个:
Timestep all
Y TESFG 1
4.0
4.0
4.0
4.2
**************编辑*****************
这是我的第二个问题!
我想要一个累积数据输出,以便对于每个时间步,它检查数据的累积值以及它是否大于最大值。它停止添加该特定行。因此在上面的示例中,如果最大值为 3.0,则不会添加最后一个时间步,结果将是:
Timestep all
Y TESFG 1
3.0
3.0
3.0
3.0
解决方案
试试这个:
with open('input.txt') as fp:
data = [float(line.strip()) for line in fp if line.strip().replace('.', '', 1).isdigit()]
mmax = 3.0
data = [data[i: i+4] for i in range(0, len(data), 4)]
res = 'Timestep all\nY TESFG 1\n' + '\n'.join([str(sum(x)) if sum(x) < mmax else str(mmax) for x in map(list, zip(*data))])
print(res)
输出:
Timestep all
Y TESFG 1
3.0
3.0
3.0
3.0
推荐阅读
- reactjs - 由于来自本地存储的路径,图像不会在 ReactJS 中显示
- html - 引导列和 justify-content-end
- spring - 如何为谓词设置连接
- python - Python 错误 ConnectionAbortedError:[WinError 10053]
- kotlin - Kotlin 多平台:JobCancellationException:父作业已完成
- c# - 我收到错误 CS7036,我不知道如何解决它
- javascript - Javascript - 如何在 ES6 类中使用“this”
- html - 如何使这种样式适用于按钮而不是锚?
- sql - 如何计算表中某列中具有相同值的行数?
- javascript - 如何将第二个底部标题添加到 Tabulator.js?