[英]How do I read a text file containing an array and place it in an array? (Python)
from numpy import *
f = open('matrix.txt', 'r')
x = []
for line in f.readlines():
y = [value for value in line.split()]
x.append(y)
f.close()
x = map(int, x)
a = array([x])
基本上,我的代码假设打开文本文件并将其放入列表 x。 然后我将 x 中的这些值更改为一个整数并将其放入数组 a 中。 有没有更快的方法来做到这一点? 顺便说一句,我的代码不起作用。
如果您使用np.loadtxt
您可能会做得更好np.loadtxt
。
import numpy as np
with open('matrix.txt', 'r') as f:
x = []
for line in f:
x.append(map(int, line.split()))
print x
print np.array(x)
matrix.txt 包含 3 行,每行 4 个数字:
1 2 3 4
5 6 7 8
9 8 7 6
如上所述,这会打印
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 8, 7, 6]]
[[1 2 3 4]
[5 6 7 8]
[9 8 7 6]]
但是,如上一个答案中所述,请考虑使用numpy.loadtxt 。 例如,如果print np.loadtxt('matrix.txt')
添加到程序中,它也会打印出来
[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 8. 7. 6.]]
差不多好了...
以下几行创建了一个您不想要的列表
y = [value for value in line.split()]
x.append(y)
因此,地图调用将失败
而不是这 2 行使用
x = [int(value) for value in line.split()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.