这就是文本文件的样子:
1.0778 0.86111
1.6173 0.94568
3.3376 1.565
1.1927 -0.90241
-1.0183 2.3423
1.0599 1.3005
-2.9829 -1.1132
-0.01103 0.69469
2.9999 1.1401
-0.12478 -0.35958
我想读入10 * 2矩阵(在本例中)
(实际上我的文字文件更长)
答案 0 :(得分:1)
在一行中使用numpy尝试此操作:
import numpy as np
print(np.loadtxt('filex_txt',dtype=np.float32))
输出:
[[ 1.0778 0.86111]
[ 1.6173 0.94568]
[ 3.3376 1.565 ]
[ 1.1927 -0.90241]
[-1.0183 2.3423 ]
[ 1.0599 1.3005 ]
[-2.9829 -1.1132 ]
[-0.01103 0.69469]
[ 2.9999 1.1401 ]
[-0.12478 -0.35958]]
答案 1 :(得分:1)
你可以试试这个:
data = [map(float, i.strip('\n').split()) for i in open('filename.txt')]
输出:
[[1.0778, 0.86111], [1.6173, 0.94568], [3.3376, 1.565], [1.1927, -0.90241], [-1.0183, 2.3423], [1.0599, 1.3005], [-2.9829, -1.1132], [-0.01103, 0.69469], [2.9999, 1.1401], [-0.12478, -0.35958]]
答案 2 :(得分:0)
jmcmurray@host ~ $ printf "1.0778 0.86111 \n 1.6173 0.94568 \n 3.3376 1.565 \n 1.1927 -0.90241 \n -1.0183 2.3423 \n 1.0599 1.3005 \n -2.9829 -1.1132 \n -0.01103 0.69469 \n 2.9999 1.1401 \n -0.12478 -0.35958 \n" > test.txt
jmcmurray@host ~ $ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> [x.split() for x in open("test.txt").readlines()]
[['1.0778', '0.86111'], ['1.6173', '0.94568'], ['3.3376', '1.565'], ['1.1927', '-0.90241'], ['-1.0183', '2.3423'], ['1.0599', '1.3005'], ['-2.9829', '-1.1132'], ['-0.01103', '0.69469'], ['2.9999', '1.1401'], ['-0.12478', '-0.35958']]