2015-05-03 50 views
0

我將這樣做的事實,我是一個新手到 Python,我正在採取我的第一個刺寫類。我想要達到的目的是讓學生根據用戶輸入來打開一組文本文件中的一個。文本文件包含這樣的信息:在一個類中搜索二維數組Python 2.7

20,21,22 
23,24,25 
26,27,28 

該文本文件被讀取爲二維數組。從該數組中讀取一個值並將其分配給一個新變量,以便可以打印此變量並在稍後計算中使用。在班級之外,我已經能夠毫無困難地做到這一點,但讓這個課程在班上工作一直令人沮喪。下面的代碼我到目前爲止的Python 2.7:

im_new = [] 

class Read(object): 
    def __init__(self, agev, table, row, col, newvar): 
     self.agevar = agev 
     self.table = table 
     self.row = row 
     self.col = col 
     self.newvar = newvar 

     display_list = [] 


     with open(self.table + str(self.agevar) + ".txt", "r") as data_file: 
      for line in data_file: 
       display_list.append(line.strip().split(',')) 

    def __str__(self): 
     self.newvar = (display_list[self.row][self.col]) 

immem = Read(40, "im", 1, 2, im_new) 


print "Immediate Memory: " % im_new 

理想的情況下,引用的例子文本文件,輸出將是「即時記憶:25」,但輸出我得到的是「即時記憶:」當我在控制檯中輸出值im_new,我得到「[]」。我確定這是非常明顯的,我錯過了。任何幫助,將不勝感激。提前致謝。

+0

我不太明白你的問題,但嘗試'打印「立即記憶:」%immem.newvar' –

+0

感謝您的幫助。我對你建議的代碼進行了修改,但是沒有結果。我同意也許我沒有解釋我做得很好。我會修改我的問題和代碼並重新發布。我很欣賞你的嘗試。 – credenzamatic

回答

0

你的代碼有問題,它也不會運行。我試圖修復:

im_new = [] 

class Read(object): 
    def __init__(self, agev, table, row, col, newvar): 
     self.agevar = agev 
     self.table = table 
     self.row = row 
     self.col = col 
     self.newvar = newvar 

     self.display_list = [] 


     with open(self.table + str(self.agevar) + ".txt", "r") as data_file: 
      for line in data_file: 
       self.display_list.append(line.strip().split(',')) 

    def __str__(self): 
     self.newvar = (self.display_list[self.row][self.col]) 
     return self.newvar 

immem = Read(40, "im", 1, 2, im_new) 


print "Immediate Memory: ", immem 

這將返回Immediate Memory: 25像你期望的,但我不知道這是你想要的。

0

這是因爲您將您的Read類指定爲immem變量,而不是im_new變量。您需要打印immem而不是im_new