Python 如何将txt文件中的数据放入网格?
我试图使用一个.txt文件,该文件的格式类似于python网格中的矩阵 下面是我用来创建网格的类:Python 如何将txt文件中的数据放入网格?,python,file,grid,Python,File,Grid,我试图使用一个.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): se
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
其中,data以字符串形式返回从文件夹格式化的数字,但我需要某种方法来单独返回每个数字,并将其设置为网格中的单元格。有什么想法吗
编辑:我的当前代码:
g = map(int, m.readline().split())
data = m.read()
matrix = Grid(g[0], g[1], 1)
g[0]和g[1]来自具有行和列变量的列表。这样,任何采用相同格式的.txt文件的第一行都将是行和列变量。
我试图弄明白,剩下的数据如何能够在不使用列表的情况下替换“1”
import numpy
a_width = 9
a_height = 9
data_file = "matrix.dat"
a = numpy.array(open(data_file).read().split(),dtype=int).reshape((a_width,a_height))
#or another alternative below
a = numpy.fromfile("matrix.dat",dtype=int,sep=" ").reshape(9,9)
print a
另一种解决方案
with open(data_file) as f:
a = map(str.split,f)
print a
这只是Nick Burns代码的一个更简洁的版本
另一种解决方案
with open(data_file) as f:
a = map(str.split,f)
print a
这只是Nick Burns代码的一个略为简洁的版本这看起来如何:
with open('matrix.txt') as f:
grid_data = [i.split() for i in f.readlines()]
这将从文件中读取每个数组,并将其格式化为值列表
希望这有帮助 这看起来怎么样:
with open('matrix.txt') as f:
grid_data = [i.split() for i in f.readlines()]
这将从文件中读取每个数组,并将其格式化为值列表
希望这有帮助 一个超级简单的答案(添加了一个新的答案,因为它比以前的答案简单得多)
我喜欢使用Grid类来填充矩阵。除了从文件中读取数据外,不使用列表
到达那里(我希望如此!)一个超级简单的答案(添加了一个新的答案,因为它比以前的答案简单得多)
我喜欢使用Grid类来填充矩阵。除了从文件中读取数据外,不使用列表
到达那里(我希望,我想!)+1为简单起见。。。但是我认为你不需要脱衣舞。。。split应该注意这一点……没有列表还有其他方法吗?这也是我的思维默认的地方,但是教授不允许在这里使用列表。这是什么让我难堪。你什么意思?不列出清单就做?您当前正在使用列表。。但是当然。。。列表是表达我最初问题的最自然的方式。我能看到的唯一方法是对数据中的行执行for循环,但这会返回与其数字分开的空格和负号…Nick,该网格只是数据的字符串表示,这就是我已经设置的数据。它不允许我从中调用单元格,(即网格[0][0]拉取整个内容,网格[0][1]超出了范围,因为它应该是1和3+1,为了简单…但我认为你不需要这个条带…split应该解决这个问题…有没有其他方法可以不用列表呢?这也是我的思维默认的地方,但教授不允许在这里使用列表。这是什么样的困扰我。你是什么意思不用列表就做s?你目前正在使用列表..但是可以肯定的是..列表只是表示我原始问题的最自然的方式。我能看到的唯一方法是对数据中的行执行for循环,但它返回的空格和负号与其数字分开…Nick,该网格只是数据的字符串表示,它是我已经设置好的数据。它不允许我从中调用单元格,(例如,网格[0][0]拖出整个内容,网格[0][1]超出了应该为1和3的范围类
Append
没有名为Append
的函数。您需要像这样传递它:my_array=array()
然后,my_array[i].append()
通过我添加到原始问题中的类数组,新建_矩阵[i]。append(j)是导致问题的原因。新建_矩阵[i]是一种数组类型,它不能/不会将j附加到itHey wes中-现在我们有了这两个类,它运行得非常好。如果在上面编辑,您可能需要在matrix.txt
中考虑第一行(9,9)
。我不知道Nick,我甚至去掉了readline().split()我让它去掉了9,9。仍然有一个超出范围的错误。不过我感谢你今晚给我的所有帮助。类Append
没有名为Append
的函数。你需要像这样传递它:my_array=array()
然后,my_array[i].Append()
通过我在原始问题中添加的类数组,new_matrix[I]。append(j)是导致问题的原因。new_matrix[I]是一种数组类型,它不能/不会将j附加到它们的wes中-现在我们有了这两个类,它运行得非常好。如果在上面进行编辑,您可能需要考虑第一行(9,9)
在matrix.txt
中。我不认识尼克,我甚至取下了readline().split(),我取下了9,9。仍然有一个超出范围的错误。不过我感谢你今晚给我的所有帮助。