我想格式化一个 numpy 数组并将其保存在 *.txt 文件中
numpy 数组如下所示:
a = [ 0.1 0.2 0.3 0.4 ... ] , [ 1.1 1.2 1.3 1.4 ... ] , ...
并且输出 *.txt 应该如下所示:
0 1:0.1 2:0.2 3:0.3 4:0.4 ...
0 1:1.1 2:1.2 3:1.3 1:1.4 ...
...
不知道该怎么做。
谢谢你。
好贾巴谢谢你。我稍微修正了你的答案
import numpy as np
a = np.array([[1,3,5,6], [4,2,4,6], [6,3,2,6]])
ret = ""
for i in range(a.shape[0]):
ret += "0 "
for j in range(a.shape[1]):
ret += " %s:%s" % (j+1,float(a[i,j])) #have a space between the numbers for better reading and i think it should starts with 1 not with 0 ?!
ret +="\n"
fd = open("output.sparse", "w")
fd.write(ret)
fd.close()
你觉得可以吗?!