[英]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.