我有一个代码可以打开样本和背景数据(每个10 ^ 5个点)并从另一个中减去一个。在第一次运行代码时,它可以完美运行。但是,当我删除背景数据并为背景选择另一个文件时,不执行减法。我发现这是由于执行“subtract_bkgr_from_magn”命令时样本数组大小加倍。会发生的事情是,在“for i in range”之前,大小是100000点,但是在此命令之后它立即变为200000.显然有一些我不知道的事情。有人可以向我解释我的代码有什么问题以及如何纠正它?
import tkinter as Tk
from tkinter.filedialog import askopenfilename
top = Tk.Tk()
class Window:
def __init__(self):
self.top = top
self.m = []
self.m_bkgr = []
self.m_true = []
Tk.Button(top, text='Sample', command=self.open_sample, width=10).pack()
Tk.Button(top, text='X', command=self.remove_bkgr).pack()
Tk.Button(top, text='Background', command=self.open_bkgr, width=10).pack()
Tk.Button(top, text='Calculate', command=self.calculate, width=7).pack()
def openfile(self):
self.opfi = askopenfilename()
def calc_file_length(self):
with open(self.opfi, 'r') as file:
for i, l in enumerate(file):
pass
self.number = i + 1
def open_sample(self):
self.openfile()
self.calc_file_length()
def open_bkgr(self):
self.opbkgr = askopenfilename()
def empty_arrays(self):
del self.m[:], self.m_bkgr[:], self.m_true[:]
def columns_for_sample(self):
with open(self.opfi, 'r') as file:
for line in range(self.number):
g = file.readline().split('\t')
if line >= 7:
self.magn = str(g[5])
self.m.append(eval(self.magn))
def column_for_bkgr(self):
if self.opbkgr:
with open(self.opbkgr, 'r') as file:
for line in range(self.number):
w = file.readline().split('\t')
if line >= 7:
self.magn_bkgr = str(w[5])
self.m_bkgr.append(eval(self.magn_bkgr))
else: # no background
pass
def subtract_bkgr_from_magn(self):
if self.opbkgr:
for i in range(len(self.m)):
self.m_true.append(self.m[i] - self.m_bkgr[i])
else: # no background
self.m_true = self.m
def calculate(self):
self.empty_arrays()
self.columns_for_sample()
self.column_for_bkgr()
self.subtract_bkgr_from_magn()
def remove_bkgr(self):
self.opbkgr = ''
del self.m_bkgr[:]
a = Window()
Tk.mainloop()
以下是我使用的数据样本(它们与样本和背景类似):
#text
#text
#text
#text
#text
#text
#text
-0.003333 -0.133333 0.010000 -0.133333 0.003333 0.000250
-0.016667 -0.100000 0.003333 0.000000 0.002083 -0.000208
0.003333 -0.066667 0.010000 -0.133333 0.002083 -0.000208
-0.003333 -0.066667 0.016667 -0.133333 0.002500 -0.000125
-0.003333 -0.100000 0.010000 -0.333333 0.003750 4.166667E-5
-0.003333 -0.066667 0.010000 -0.266667 0.002500 0.000375
-0.003333 -0.066667 0.003333 -0.133333 0.002917 0.000667