每个文本文件行python 3创建多个3x3网格

时间:2016-09-08 00:24:17

标签: python-3.5

我正在尝试在文本文件中每行创建一个3x3网格。该文件有多行数字,但每行只有9个数字,如下所示:

4 5 6 7 8 9 1 2 3

1 2 3 4 5 6 7 8 9

5 6 4 7 9 8 3 2 1

我似乎无法弄清楚如何将每一行放入网格中。所以我需要它看起来像这样:

4 5 6

7 8 9

1 2 3

到目前为止,这是我的代码,但我可能很容易出错:

f = open("numbers.txt")
    grid = []
    rowIndex = 3
    columnIndex = 3
    for lines in f:
        lines.split()
    for row in range(rowIndex):
        grid.append([0]*columnIndex)

它还需要使用maping将字符串转换为int。任何帮助都是非常有用的。感谢

1 个答案:

答案 0 :(得分:0)

所以它不清楚你想如何存储每个网格/线,但在这个例子中我只是将它附加到一个列表,你可以用你的网格做任何你需要的东西:

f = open("numbers.txt","r")
lines = filter(None, (line.rstrip() for line in f))
list_of_grids = [] #this will contain each line of the file as a grid
for line in lines:
    grid = [] #each line should be a grid
    n = 0
    row = []
    for number in line:
        try: #try to convert the string to an int
            num_to_append = int(number)
            row.append(num_to_append)
            n += 1
        except:
            pass #it's a space, ignore
        if (n!= 0) and n % 3 == 0:
            grid.append(row) #row is ready, added to the line grid
            row = []
            n = 0
    list_of_grids.append(grid) #append each line to the master grid

这将产生一个像这样的网格列表,它可以很容易地改变,但你想看起来像:

[
  [[4, 5, 6],
   [7, 8, 9],
   [1, 2, 3]],

  [[1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]],

  [[5, 6, 4],
   [7, 9, 8],
   [3, 2, 1]]
]