[英]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.