python将txt格式化_python-格式化numpy数组并保存到* .txt

本文介绍如何将numpy数组格式化并保存到.txt文件中,提供了一个简单的解决方案,通过遍历数组并利用字符串格式化方法完成任务。讨论了不同写入方式的效率,并提供了多种写入方法的示例。
摘要由CSDN通过智能技术生成

我想格式化一个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()

您认为可以吗?

解决方法:

相当简单:

import numpy as np

a = np.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值