如何遍历列表,在每个时间步更改列表元素,添加或减去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文件中的输入值。
V = [1,2,3,4,5]

f = open(\'Qin.txt\')     # values in Qin.txt: 1,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
    

解决方法

        要么:
V = [1,2,3,4,5]

f = open(\'Qin.txt\')     # values in Qin.txt: 1,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,2.0,3.0],[-2.0,2.0]]
或在其他情况下(如果我误解了您的格式):
V = [1,2 
fdata = map(float,f.readlines())
f.close()

g = open(\'Qout.txt\')    # values in Qout.txt: 4,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 = [1,g.readlines())
g.close()

for i,y in enumerate(gdata):
    for j,v in enumerate(V):
        V[j] = v + fdata[i] - y
    print V
    ,        由于缩进似乎丢失了,因此很难确切说明您当前的算法出了什么问题。但我怀疑这与在f中的每一行读取g中的每一行有关,当您似乎想在f中的第0行与g中的第0行以及在f中的第1行与g中的第1行一起使用时,等等 我认为这种算法将满足您的需求...
V = [1,5]
f = open(\'Qin.txt\')     # values in Qin.txt: 1,2 
g = open(\'Qout.txt\')    # values in Qout.txt: 4,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
    ,        首先,第四次访问
f
,您将不会再得到
1
,因为您已经读取了所有数据一次。因此,在处理数据之前,应将数据读入变量
f
g
中。如果您执行以下操作:
f = open(\'Qin.txt\').readlines()  
g = open(\'Qout.txt\').readlines()
然后您将获得:
[-2.0,2.0]
[-3.0,-2.0,1.0]
[-3.0,1.0]
[0.0,3.0,4.0]
[-1.0,3.0]
[-1.0,3.0]
[-2.0,2.0]
[-2.0,2.0]
这些是您从上面指定的计算中获得的结果。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...