【问题标题】:Creating multiple 3x3 grids per text file line python 3每个文本文件行python 3创建多个3x3网格
【发布时间】:2017-01-15 18:58:12
【问题描述】:

我正在尝试在文本文件中每行创建一个 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)

它还需要使用映射将字符串转换为 int。非常感谢任何帮助。谢谢

【问题讨论】:

  • 您是否尝试过为此使用numpy?会好很多。
  • 另外,你打算如何表示矩阵结构?作为列表列表?

标签: python-3.5


【解决方案1】:

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

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]]
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2021-09-17
    • 1970-01-01
    • 2018-01-31
    相关资源
    最近更新 更多