【问题标题】:list generator/comprehension for reading from file and putting in list用于从文件中读取并放入列表的列表生成器/理解
【发布时间】:2014-04-03 12:06:31
【问题描述】:

假设我从创建一个类开始,变量为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'  

【问题讨论】:

  • 您认为为什么需要生成器语句?
  • 不一定“需要”一个,我只是觉得会很好。
  • 你为什么不发布你的代码并提出一个问题?
  • 生成器在被消耗时工作。什么会消耗这个过程?

标签: python python-2.7 generator


【解决方案1】:
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')))

【讨论】:

    猜你喜欢
    • 2023-01-26
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2018-08-19
    • 2020-07-13
    • 2021-02-25
    相关资源
    最近更新 更多