【发布时间】:2016-04-14 07:38:23
【问题描述】:
如果您能就这个问题给我任何提示,我将不胜感激。我该如何启动它,有什么想法吗?
我正在运行一个产生能量的软件。我有 N 个时间步(块),并且在每个时间步中它会生成几行。第一列是每个时间步中生成的行数的计数器。因此,我将有一个如下所示的文本文件,它是一个大文件的简化示例:
#Block: 3 3 0
1 -0.3746468365E+04 0.9420348015E+00 -0.3745526330E+04 0.1636348407-151 316.8679 0.2626532250-312
2 -0.3746707738E+04 0.1149418891E+01 -0.3745558319E+04 0.1220432713E+00 386.6247 0.2626532250-312
3 -0.3746757823E+04 0.1195378991E+01 -0.3745562444E+04 0.1636348407-151 402.0841 0.2626532250-312
#Block: 4 4 1
1 -0.3746625102E+04 0.6261182789E+00 -0.3745998983E+04 0.1636348407-151 210.6045 0.2626532250-312
2 -0.3746723956E+04 0.7190568481E+00 -0.3746004899E+04 0.1636348407-151 241.8658 0.2626532250-312
3 -0.3746758909E+04 0.7514702248E+00 -0.3746007439E+04 0.1636348407-151 252.7685 0.2626532250-312
4 -0.3746707738E+04 0.7067911904E+00 -0.3746000947E+04 -0.3205844292E+00 237.7401 0.2626532250-312
5 -0.3746680579E+04 0.6897161187E+00 -0.3745990863E+04 0.1636348407-151 231.9966 0.2626532250-312
#Block: 5 5 1
1 -0.3746625102E+04 0.6261182789E+00 -0.3745998983E+04 0.1636348407-151 210.6045 0.2626532250-312
2 -0.3746723956E+04 0.7190568481E+00 -0.3746004899E+04 0.1636348407-151 241.8658 0.2626532250-312
3 -0.3746758909E+04 0.7514702248E+00 -0.3746007439E+04 0.1636348407-151 252.7685 0.2626532250-312
4 -0.3746707738E+04 0.7067911904E+00 -0.3746000947E+04 -0.3205844292E+00 237.7401 0.2626532250-312
5 -0.3746680579E+04 0.6897161187E+00 -0.3745990863E+04 0.1636348407-151 231.9966 0.2626532250-312
我想计算这些数据的第 3 列的运行平均值并保存在“平均文本文件”中。因此,
文本文件中的第一个值应该是块 1 的第 3 列的平均值。 (前 3 个值 = (3.5+7.1+5.4)/3)
文本文件中的第二个值应该是块 1 和块 2 的第 3 列的平均值。 (前 8 个值 = (3.5+7.1+5.4+2.5+1.1+5.4+4.4+1.4)/8)
文本文件中的第三个值应该是块 1 和块 2 和块 3 的第 3 列的平均值。 (前 12 个值 = (3.5+7.1+5.4+2.5+1.1+5.4+4.4+1.4+3.5+1.1+8.1+9.4)/12)
我有 N 个块。实际上,我正在计算所有块的第 3 列的平均值作为时间步长的函数。
这是我尝试过的
with open('xxx.txt','r') as file:
groups = [] # Will contain the final data
current_group = [] # Temporary
line = file.readline()
while line != "":
if line.startswith("#Block"):
# Store the current group and start a new one
groups.append(current_group)
current_group = []
else:
# Add the number to the current group
current_group.append(float(line.split()[2]))
line = file.readline()
averages = list()
for i in xrange(len(groups)):
flatten_list = list(itertools.chain(*groups[:i+1]))
print (flatten_list)
averages.append(sum(flatten_list) / len(flatten_list))
with open('output.txt', 'a+') as output_f:
output_f.writelines(averages)
【问题讨论】:
-
我试过了,但我真的不知道如何制作文件。我更新了问题
-
请在标签中添加
python-3.x。
标签: python python-3.x moving-average