簡體   English   中英

讀取並添加從文本文件中提取的數組中的最后一個值

[英]Read and add the last value from an array pulled from a text file

這是一個示例:我有四個時間段,分別標記為t = 0,t = 1,t = 2,t = 3。 每次都有一個與之關聯的值,如下所示:

文本文件的格式如下:
0,213
1,-999
2,456
3,-1100

基本上,每個值都在一個周期內。 我想做的就是使用這些值並將所有值都設為t = 0。 如果我繪制時間線,那么在t = 0和t = 2時我將有兩個正值,在t = 1和t = 3時我將有兩個負值。

現在,我想從時間軸的右側移到左側以達到t = 0。 因此,在t = 3處(即時間軸中的最后一個值),需要將兩個單位向左移動,以將它們添加到t = 1的值中,因為它們都在負側,然后最終將該值從t =中移出1至t = 0。 同樣,對於積極方面,我將需要這樣做。

以下是我的代碼。 可能不正確,但我正在嘗試:

import numpy as np

workspace = 'C:\\Users\MM\Desktop'

time= np.loadtxt(workspace +'\\Assign1.txt', delimiter = ',', usecols = range(1))
value = np.loadtxt(workspace +'\\Assign1.txt', delimiter = ',', usecols = range(1,2))
for x in time:
    x+1;
    print(x)

for y in value:
    y+1
    print(y[-1])   
# I want this to read the last value(-1100) from the array
# of the text file I have. I already got the values 
# pulled from the text file. It gives me an error.

如果確實可以使用,則由於這是一個負值,因此需要將其添加到先前的負值,依此類推。

我的內容只是一個示例。 時間值可以大於或小於4,並且負值和正值可以在時間軸上的任何位置。 目的是獲得t = 0時的所有負值和正值,並查看負值是否等於正值。 如果其中一個值大於1但小於或等於15,則需要將這些值視為相等。

代數上,您所描述的內容比您所計划的過程要簡單得多。 您將所有數字相加,然后查看結果是否在[-15,15]范圍內。 使用此條件檢查替換兩個預期的循環:

if -15 <= sum(value) <= 15:
    # Here, insert the code for matching stuff.

至於為什么給定的代碼失敗...循環是不正確的。 我不確定您要使用兩個+1表達式做什么; 它們不會以任何方式影響數據流,因為您不存儲值。

第二個循環很混亂。 在每次迭代中,您都從列表中選擇一個值。 您的print語句也將該單個值視為一個列表(您可以在Python中創建一個列表列表,但該程序不會這樣做)。 當您嘗試訪問單個整數的最后一個元素時,Python會告知您混亂情況。

要打印列表的最后一個值,只需使用print value [-1] ; 不要遍歷整個列表以找到最后一個項目。


就是說,我們現在有了原始問題:如何使用您描述的算法對負值和正值求和。 您需要以相反的順序運行列表。 我將在兩個循環中執行此操作,每個循環分別表示正負:

time = range(10)
value = [213, -999, 456, -1100, -16, 5, 42, -80, 9, 10]

last_neg = 0
for i in range(len(value)-1, -1, -1):   # Go through the list in reverse order
    if value[i] < 0:
        value[i] += last_neg
        last_neg = value[i]

last_pos = 0
for i in range(len(value)-1, -1, -1):   # Go through the list in reverse order
    if value[i] > 0:
        value[i] += last_pos
        last_pos = value[i]

print "pos & neg sums", value[0], value[1]
value[0] += value[1]

print "grand sum", value[0]

print "Check the summation:", value

輸出:

pos & neg sums 735 -2195
grand sum -1460
Check the summation: [-1460, -2195, 522, -1196, -96, 66, 61, -80, 19, 10]

暫無
暫無

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

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