Python 如何在列表中循环,在每个时间步更改列表元素,添加或减去txt文件中的输入值?
为什么我不能按这个顺序得到以下结果? [-2.0, -1.0, 0.0, 1.0, 2.0] [-1.0, 0.0, 1.0, 2.0, 3.0] [-2.0,-1.0,0.0,1.0,2.0],相反,我在错误的位置得到了第二个列表。 考虑到这种形式的输入数据,我能否以更一致的方式编辑列表元素? 我的目标是在每个时间步更改初始列表(V),添加或减去txt文件中的输入值Python 如何在列表中循环,在每个时间步更改列表元素,添加或减去txt文件中的输入值?,python,Python,为什么我不能按这个顺序得到以下结果? [-2.0, -1.0, 0.0, 1.0, 2.0] [-1.0, 0.0, 1.0, 2.0, 3.0] [-2.0,-1.0,0.0,1.0,2.0],相反,我在错误的位置得到了第二个列表。 考虑到这种形式的输入数据,我能否以更一致的方式编辑列表元素? 我的目标是在每个时间步更改初始列表(V),添加或减去txt文件中的输入值 V = [1,2,3,4,5] f = open('Qin.txt') # values in Qin.txt: 1,
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1, 3, 2
g = open('Qout.txt') # values in Qout.txt: 4, 5, 5
for line in f:
Z=float(line)
for line in g:
G=float(line)
c = []
for i in range(len(V)):
c.append(V[i]+Z-G)
print c
首先,第四次访问
f
时,您将不会再次获得1
,因为您已经读取了所有数据一次。因此,在处理数据之前,应将数据读入变量f
和g
。如果您执行以下操作:
f = open('Qin.txt').readlines()
g = open('Qout.txt').readlines()
然后你会得到:
[-2.0, -1.0, 0.0, 1.0, 2.0]
[-3.0, -2.0, -1.0, 0.0, 1.0]
[-3.0, -2.0, -1.0, 0.0, 1.0]
[0.0, 1.0, 2.0, 3.0, 4.0]
[-1.0, 0.0, 1.0, 2.0, 3.0]
[-1.0, 0.0, 1.0, 2.0, 3.0]
[-1.0, 0.0, 1.0, 2.0, 3.0]
[-2.0, -1.0, 0.0, 1.0, 2.0]
[-2.0, -1.0, 0.0, 1.0, 2.0]
这些是您将从上面指定的计算中得到的结果。很难准确判断当前算法的错误,因为缩进似乎丢失了。但我怀疑它与每一行读取一次g中的每一行有关,当你想用f中的0行和g中的0行,用f中的1行和g中的1行,等等 我想这个算法会满足你的要求
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1, 3, 2
g = open('Qout.txt') # values in Qout.txt: 4, 5, 5
fItems = []
for line in f:
fItems.append(float(line))
lineNum = 0
for line in g:
c = []
for i in range(len(V)):
c.append(V[i]+fItems[lineNum]-float(line))
print c
lineNum+=1
或:
或者如果在另一种情况下(如果我误解了您的格式):
或者,如果您想修改V每个步骤(请注意,它将不等于问题中提到的结果,因此我的代码只是如何执行此操作的示例):
c.append(V[i]+Z-G)
应该缩进,但这会导致缩进错误
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1, 3, 2
fdata = f.readlines()
f.close()
g = open('Qout.txt') # values in Qout.txt: 4, 5, 5
gdata = g.readlines()
g.close()
output = [[v + float(x) - float(y) for v in V] for y in gdata for x in fdata]
print output
>>> [[-2.0, -1.0, 0.0, 1.0, 2.0], [-1.0, 0.0, 1.0, 2.0, 3.0], [-2.0, -1.0, 0.0, 1.0, 2.0]]
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1, 3, 2
fdata = map(float, f.readlines())
f.close()
g = open('Qout.txt') # values in Qout.txt: 4, 5, 5
gdata = map(float, g.readlines())
g.close()
output = [[v+fdata[i]-y for v in V] for i,y in enumerate(gdata)]
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1, 3, 2
fdata = map(float, f.readlines())
f.close()
g = open('Qout.txt') # values in Qout.txt: 4, 5, 5
gdata = map(float, g.readlines())
g.close()
for i,y in enumerate(gdata):
for j,v in enumerate(V):
V[j] = v + fdata[i] - y
print V