【问题标题】:Appending rows to make matrix in python from text file从文本文件中追加行以在 python 中创建矩阵
【发布时间】:2017-06-14 19:17:21
【问题描述】:

我有一个带有这种形式的矩阵的文本文件:http://textuploader.com/d0qmb 每个整数必须在矩阵中占据自己的位置。我编写了这段代码,允许我为矩阵中的每一行打印数组,但我不知道如何附加每个数组来创建矩阵。

import numpy as np

# rows, cols not used in code. Just for info
rows = 9
cols = 93

with open('bob.txt') as f:
 while True:
    i=0
    str = f.readline()
    str = str.strip()
    d = list(str)
    d = map(int, d)
    if not str: break
    print(d)
    i += 1

【问题讨论】:

  • 创建一个列表并使用 append 在该列表中追加一个列表

标签: python loops numpy matrix text-files


【解决方案1】:
import numpy as np

array = []
with open('bob.txt', 'r') as f:
    for line in f:
        array.append(array.append([int(i) for i in list(line) if i.isdigit()]))

numpy_array = np.array(array)

[int(i) for i in list(line) if i.isdigit()] 在 python 中是a list comprehension

这与以下内容大致相同:

for character in line:
    if character is:
        cast this character to an int and append it to the list

【讨论】:

  • 我收到了这个错误:ValueError: invalid literal for int() with base 10: ''
  • 您使用的不是提供的示例吗?是否涉及花车?
  • 不,我正在使用我提供的文本文件。
  • 哦,你有一些空间没有显示给我。一秒钟我会修好它
  • @rajkarthikkumar 我已经解决了这个问题,它对我有用。现在对你有用吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 2018-11-11
  • 1970-01-01
  • 2017-03-20
  • 2014-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多