将2D数组写入文本文件 [英] Write a 2D array to a text file
本文介绍了将2D数组写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个二维数组,我想将其写入文件,该数组看起来几乎像这样:
I have a 2d array and i want to write it to a file, the array looks almost like this:
>>print (arr)
[0 0 20
0 5 520
2 0 720
....
8 -20 150
0 10 10]
当我尝试将其写入文件时,将其保存为最后的输出,这是我使用的内容:
when i tried to write it to a file it was saved as the last output, here what i used:
ff = open('output.txt', 'w')
ff.write(arr)
这是文件中的结果
[0 0 20
0 5 520
2 0 720
....
8 -20 150
0 10 10]
我在该网站的另一个问题中看到了一个解决方案 但我还是有问题,
i saw a solution in another question in this website but still i have a problem,
np.ndarray.tofile(arr,"output.txt",'\n','%s')
文件中的输出如下:
0 0 20 0 50 ...
依次类推,直到数组末尾
and so on till the end of the array
我希望输出看起来像这样:
i want the output to look like this:
0 0 20
0 5 520
2 0 720
.
.
.
8 -20 150
0 10 10
推荐答案
您可以将数组拆分为多个块,然后分别编写每个块.
You could split your array into chunks and write each chunk separately.
类似的东西应该可以帮助您入门:
Something like this should get you started:
myarr = [1,10,100,2,20,200,3,30,300,4,40]
def split_to_chunks(myarray, e):
return (myarray[i:i+e] for i in xrange(0, len(myarray), e))
for i in split_to_chunks(myarr, 3):
# etc
这篇关于将2D数组写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文