簡體   English   中英

在類python 2.7中搜索2D數組

[英]Search 2D array in a class Python 2.7

我會以我是Python的新手的事實為框架,而我正在嘗試編寫類。 我想要實現的是讓該類根據用戶輸入打開一組文本文件中的一個。 文本文件包含以下信息:

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

文本文件被讀取為2D數組。 從該數組中讀取一個值,並將其分配給新變量,以便可以打印該變量,並在以后的計算中使用該變量。 我可以在課堂外毫無困難地做到這一點,但是在課堂上使用它卻令人沮喪。 到目前為止,這是我為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

理想情況下,引用示例文本文件,輸出將為“ Immediate Memory:25”,但是我得到的輸出為“ Immediate Memory:”,當我在控制台中打印值im_new時,我將獲得“ []”。 我敢肯定,我很想念這件事。 任何幫助,將不勝感激。 提前致謝。

您的代碼有問題,它也無法運行。 我試圖解決:

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正如您所期望的那樣,但是我不確定這是否是您想要的。

暫無
暫無

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

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