簡體   English   中英

如何在每個時間步驟中循環更改列表元素的列表,添加或減去txt文件中的輸入值?

[英]How can I loop through a list changing the list elements at each time step, adding or subtracting input values that are in the txt files?

為什么我不能按此順序得到以下結果? [-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, 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

要么:

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 = [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

很難確切地說出當前算法的確切錯誤,因為縮進似乎丟失了。 但是我懷疑它與f中的每一行讀取g中的每一行有關,當看起來你想要使用f中的第0行,g中的第0行和f中第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

首先,第四次訪問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]

這些是您從上面指定的計算中得到的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM