【问题标题】:How to create a 2d nested list from a text file using python?如何使用 python 从文本文件创建二维嵌套列表?
【发布时间】:2021-12-28 19:52:00
【问题描述】:

我是一名初级程序员,我正试图弄清楚如何从特定的文本文件创建一个二维嵌套列表(网格)。例如,文本文件如下所示:

3
3
150
109
80
892
123
982
0
98
23

文本文件中的前两行将用于创建网格,这意味着它是 3x3。接下来的 9 行将用于填充网格,前 3 行构成第一行,接下来的 3 行构成中间行,最后 3 行构成最后一行。所以嵌套列表看起来像这样:

[[150, 109, 80] [892, 123, 982] [0, 98, 23]]

我该怎么做呢?我能够列出所有内容,但我不知道如何使用前 2 行来定义外部列表中内部列表的大小:

lineContent = []
innerList = ?
     for lines in open('document.txt','r'):
     value = int(lines)
     lineContent.append(value)

从这里开始,我该去哪里使用前 2 行的给定值将其转换为嵌套列表?

提前致谢。

【问题讨论】:

    标签: python list nested grid


    【解决方案1】:
    def parse_txt(filepath):
        lineContent = []
        with open(filepath, 'r') as txt:  # The with statement closes the txt file after its been used
            nrows = int(txt.readline())
            ncols = int(txt.readline())
            for i in range(nrows): # For each row
                row = []
                for j in range(ncols):  # Grab each value in the row
                    row.append(int(txt.readline()))
                lineContent.append(row)
        return lineContent
    
    grid_2d = parse_txt('document.txt')
    

    【讨论】:

      【解决方案2】:

      您可以使用列表推导使这变得非常整洁。

      def txt_grid(your_txt):    
          with open(your_txt, 'r') as f:
              # Find columns and rows
              columns = int(f.readline())
              rows = int(f.readline())
              your_list = [[f.readline().strip() for i in range(rows)] for j in range(columns)]
          return your_list
      
      print(txt_grid('document.txt'))
      

      strip() 只是在将每行的换行符 (\n) 存储到列表中之前清除它们。

      编辑:修改后的版本,如果您的 txt 文件没有足够的行用于定义的维度。

      def txt_grid(your_txt):    
          with open(your_txt, 'r') as f:
              # Find columns and rows
              columns = int(f.readline())
              rows = int(f.readline())
              dimensions = columns * rows
      
              # Test to see if there are enough rows, creating grid if there are
              nonempty_lines = len([line.strip("\n") for line in f]) # This ignores the first two lines as they have already been written
              if nonempty_lines < dimensions:
                  # Either raise an error
                  # raise ValueError("Insufficient non-empty rows in text file for given dimensions")
                  # Or return something that's not a list
                  your_list = None
              else:
                  # Creating grid
                  your_list = [[f.readline().strip() for i in range(rows)] for j in range(columns)]
          return your_list
      
      print(txt_grid('document.txt'))
      

      【讨论】:

        【解决方案3】:
        lineContent = []
        innerList = []
        for lines in open('testQuestion.txt', 'r'):
            value = int(lines)
            lineContent.append(value)
        
        rowSz = lineContent[0]  # row size
        colSz = lineContent[1]  # column size
        del lineContent[0], lineContent[0]  # makes line contents just the values in the matrix, could also just start currentLine at 2, notice 0 index is repeated because 1st element was deleted 
        
        assert rowSz * colSz == len(lineContent), 'not enough values for array' # to ensure there are enough entries to complete array of rowSz * colSz elements
        
        arr = []
        currentLine = 0
        for x in range(rowSz):
            arr.append([])
            for y in range(colSz):
                arr[x].append(lineContent[currentLine])
                currentLine += 1
        
        print(arr)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-05-27
          • 1970-01-01
          • 2020-12-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多