【问题标题】:Iteration to update 2 dimensional array迭代更新二维数组
【发布时间】:2014-05-30 15:49:12
【问题描述】:

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

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

然而行当前是数组[(1, 1, 1)],很明显,部分迭代工作正常。如何让矩阵正确更新值。

【问题讨论】:

    标签: python arrays numpy iteration


    【解决方案1】:

    您需要在while 循环之前将j 重置为零。

    【讨论】:

      【解决方案2】:

      使用

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

      让文件自动为您关闭。它看起来更好,您不必记得关闭文件。

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

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

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

      【讨论】:

        猜你喜欢
        • 2011-12-28
        • 2015-04-04
        • 2020-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-08
        • 1970-01-01
        相关资源
        最近更新 更多