如何在每个时间步骤循环遍历列表并根据txt文件中的输入值修改列表元素?

3 投票
3 回答
655 浏览
提问于 2025-04-16 20:10

我为什么得不到以下这个顺序的结果呢? [-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),通过添加或减去文本文件中的输入值。

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

3 个回答

0

首先,当你第四次访问 f 时,你不会再得到 1 了,因为你已经把所有的数据都读过一次了。所以,在处理数据之前,你应该先把数据读入变量 fg 中。如果你这样做:

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]

这些是你从上面指定的计算中得到的结果。

1

很难准确判断你现在的算法哪里出问题,因为缩进好像丢失了。不过我猜可能是因为你在处理每一行时,是把文件g的每一行都读了一遍,而你其实想要的是把文件f的第0行和文件g的第0行对应起来,第1行和第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
2

或者:

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(注意,这样的V不会等于你问题中提到的结果,所以我的代码只是一个示例,告诉你怎么做):

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

撰写回答