2016-03-19 109 views
-2

我想知道是否有可能,或者如果我以錯誤的方式去解決它。切片??附加列表Python

我有一個if語句正在檢查外部文件的標準。然後顯示結果(所有這些工作)。使用結果中顯示的兩個數字,我需要計算一個數量,並在顯示的每條記錄的結果旁邊打印。

我想要的是:一次打印附加列表1中的每個項目,例如,當記錄1被打印時,顯示計算的項目1,記錄2打印,它顯示計算的項目2。

numberofItemsData來自我的程序中的其他代碼,它正在分割,附加和排序我的.txt文件。

def opt(): 
    calc = [] 

    for i in range (numberOfItems): 
     nextRecord = Data[i] 
     no1 = (nextRecord[0]) 
     date = (nextRecord[1]) 
     no2 = (nextRecord[2]) 
     no3 = int(nextRecord[3]) 
     rank = (nextRecord[4]) 
     no4 = int(nextRecord[5]) 

     if no4 < no3: 
      calc.append(no4 - no3) 
      print (no1, "\t\t\t", no2, "\t\t", no3, "\t\t", no4, "\t\t", calc) 
+2

你的問題不清楚。 「眉毛」與你的問題有什麼關係?什麼是數據?什麼是'numberOfItems?什麼是'a'和'b'?什麼是一套?實際上期望的輸出是什麼?請閱讀[問]。 – Goyo

+0

另外,你有沒有縮進問題?你的if語句不是爲了在for循環中而縮進嗎? – mgc

+0

編輯我的代碼/文章。複製其中的問題/錯誤。 –

回答

0

如果我理解正確的問題,你不希望有calcprint呼叫的最後一行的末尾,而是要打印剛剛追加到calc上的項目上一行。

最明顯的方式做到這一點是當你想打印簡單地重新計算值:

print(no1, "\t\t\t", no2, "\t\t", no3, "\t\t", no4, "\t\t", no4 - no3) 

或者,你可以節省計算作爲附加和打印前一個變量(這將使更有意義,如果計算是昂貴的,它其實並不重要減去兩個整數):

val = no4 - no3 
calc.append(val) 
print(no1, "\t\t\t", no2, "\t\t", no3, "\t\t", no4, "\t\t", val) 

最後一個選項是把價值從calc列表後面。您可以通過將calc-1建立索引來獲取列表中的最後一項。這是你特別要求的,但沒有太多的理由這樣做:

print(no1, "\t\t\t", no2, "\t\t", no3, "\t\t", no4, "\t\t", calc[-1])