我正在尝试使用一个 .txt 文件,该文件的格式看起来像一个 python 网格中的矩阵。
这是我用来创建网格的类:
class Grid(object):
"""Represents a two-dimensional array."""
def __init__(self, rows, columns, fillValue = None):
self._data = Array(rows)
for row in xrange(rows):
self._data[row] = Array(columns, fillValue)
def getHeight(self):
"""Returns the number of rows."""
return len(self._data)
def getWidth(self):
"Returns the number of columns."""
return len(self._data[0])
def __getitem__(self, index):
"""Supports two-dimensional indexing with [][]."""
return self._data[index]
def __str__(self):
"""Returns a string representation of the grid."""
result = ""
for row in xrange(self.getHeight()):
for col in xrange(self.getWidth()):
result += str(self._data[row][col]) + " "
result += "\n"
return result
它使用另一个名为 Array 的类来构建一维数组并将其变为二维数组。代码:Grid(10, 10, 1)
将返回一个包含 10 行和 10 列的二维数组,网格中的每个数字都是 1。
这是数组类
class Array(object):
"""Represents an array."""
def __init__(self, capacity, fillValue = None):
"""Capacity is the static size of the array.
fillValue is placed at each position."""
self._items = list()
for count in xrange(capacity):
self._items.append(fillValue)
def __len__(self):
"""-> The capacity of the array."""
return len(self._items)
def __str__(self):
"""-> The string representation of the array."""
return str(self._items)
def __iter__(self):
"""Supports traversal with a for loop."""
return iter(self._items)
def __getitem__(self, index):
"""Subscript operator for access at index."""
return self._items[index]
def __setitem__(self, index, newItem):
"""Subscript operator for replacement at index."""
self._items[index] = newItem
我希望 1 是我拥有的文本文件中的值,如下所示:
9 9
1 3 2 4 5 2 1 0 1
0 7 3 4 2 1 1 1 1
-2 2 4 4 3 -2 2 2 1
3 3 3 3 1 1 0 0 0
4 2 -3 4 2 2 1 0 0
5 -2 0 0 1 0 3 0 1
6 -2 2 1 2 1 0 0 1
7 9 2 2 -2 1 0 3 2
8 -3 2 1 1 1 1 1 -2
9,9 代表矩阵的行和列。我可以使用列表的唯一地方是readline().split()
将第一行变成列表的方法。
我当然有台词;
m = open("matrix.txt", "r")
data = m.read
其中数据以字符串表示形式返回数字,因为它们是从文件夹中格式化的,但我需要一些方法来单独返回每个数字并将其设置为网格中的单元格。有任何想法吗?
编辑:我当前的代码:
g = map(int, m.readline().split())
data = m.read()
matrix = Grid(g[0], g[1], 1)
g[0] 和 g[1] 来自具有行和列变量的列表。这样,任何遵循相同格式的 .txt 文件的第一行都是行和列变量。我试图弄清楚其余数据如何在不使用列表的情况下替换“1”。