我有一个文件,内容为
18
21
24
27
30
以及数组
[[ 1 6 11]
[ 2 7 12]
[ 3 8 13]
[ 4 9 14]
[ 5 10 15]]
如何将此数组写入文件,以便每一行都与适当的行相对应,例如它变成这样:
18 1 6 11
21 2 7 12
24 3 8 13
27 4 9 14
30 5 10 15
我已经使用了这段代码,但是它并没有按照我想要的方式编写代码。代码:
import numpy as np
ourlist = []
for i in range(1, 16):
ourlist.append(i)
mydata = np.matrix([ourlist])
array_from_list=(mydata.reshape(3, 5))
x_transpose = (np.transpose(array_from_list)) # the array above
with open('5rows.txt','a') as f: #the file containing numbers
for elements in x_transpose:
f.write(str(elements))
f.write('\n')
它将元素写入行尾。如果可能的话,您能告诉我该怎么做吗?我非常感谢您的帮助!
最佳答案
下面的代码可能会解决您的问题,尽管它的性能不是很好。您也许可以改进解决方案以更好地满足您的需求。
import numpy as np
ourlist = []
for i in range(1, 16):
ourlist.append(i)
mydata = np.matrix([ourlist])
array_from_list=(mydata.reshape(3, 5))
x_transpose = (np.transpose(array_from_list))
with open('file.txt', 'r') as f:
lines = f.readlines()
with open('file.txt', 'w') as f:
i = 0
for line in lines:
f.write(str(int(line)) + " " + str(x_transpose[i])[1:-1][1:-1] + "\n")
i+=1
关于Python:将数组逐行写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44490630/