迭代以更新二维数组

锡德

嗨,基本上我有基本的文本文件:

3
1 0 1
0 1 0
1 1 1

我正在尝试创建一个二维数组,其中包含作为整数的值。
到目前为止,我的代码是:

import numpy as np
f = open('perc.txt', 'r')
n = f.readline()
j = 0
dim = int(n.rstrip(' \n'))
mat = np.zeros((dim, dim))
for i in range(dim):
    n = f.readline()
    line = n.rstrip(' \n')
    line = line.split()
    line = map(int,line)
    while j < dim: 
        mat[i][j] = line[j]
        j += 1

但是,当我运行代码时,结果是:

1 0 1
0 0 0
0 0 0

但是line当前是array [(1,1,1)]如此清晰,以至于迭代的一部分正常工作。我如何获取矩阵以正确更新值。

马修

使用

with open(...) as outfile:
    #outfile.write()
    #outfile.read()
    #outfile.readlines()
    #etc

使文件自动为您关闭。看起来更好,您不必记住要关闭文件。

我只是读了整个内容,然后将字符串分成一个列表。然后,我使用索引来创建数组。

arr = np.array([lines[1:])lines从第二个元素开始创建每个元素的平面数组,因此我使用函数dim x dim提供的调整了它的大小resize

import numpy as np

lines = []

with open('perc.txt', 'r') as outfile:
    lines = outfile.read().split()

>>> print lines
>>> ['3', '1', '0', '1', '0', '1', '0', '1', '1', '1']

arr = np.array([lines[1:]])

dim = int(lines[0])

arr.resize(dim, dim)

>>> print arr
>>> [['1' '0' '1']
     ['0' '1' '0']
     ['1' '1' '1']]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章