假设我开始使用变量self.memory = [None] * 10000
创建一个类。
现在我的文件结构如下:
1 1231
2 1231
3 asdma
4 landsl
我想创建一个生成器语句,它将读取文件的每一行,并将其放在self.memory变量的指定索引处(左侧数字)。 这样的陈述可能吗?
编辑:添加我目前正在使用的内容:
def AbsoluteLoader(self, f):
with open(f, 'r') as assembly:
for line in assembly:
c = line.split()
if int(c[0]) == -1:
self.pc = long(c[1])
break
try:
self.memory[int(c[0])] = long(c[1])
except:
print 'invalid'
答案 0 :(得分:0)
class MyClass:
def __init__(self, fname, lines=10000):
self.pc = None
self.memory = mem = [0L] * lines
with open(fname) as inf:
for line in inf:
ndx, num = line.split()
ndx = int(ndx)
num = long(num)
try:
mem[ndx] = num
except IndexError:
if ndx == -1:
self.pc = num
break
else:
raise ValueError('invalid entry: {}'.format(line.rstrip('\r\n')))