python格式化输出format

python格式化输出

将数据输出到文件中时:格式简单,数据类型单一的数据输出用numpy.savetxt方便快捷。格式复杂数据类型多样的数据(尤其是结构化数组)使用python自带的format功能更全面。

打印数组到屏幕

# 下面的效果相同
print('{} {:n} {}/n'.format("This is the",1,"example."))
print('{0} {1:2n} {2:s}/n'.format("This is the",1,"example."))

输出numpy数组到txt文本

import numpy as np
a = np.random.rand((10,3))
f = open("out.txt",'w')
for i in range(a.shape[0]):
  f.write('{0[0]} {0[1]} {0[2]}'.format(a[i,:])) #{}内部的数组代表所匹配的format后面括号内变量
  f.write('{0[0]:<5.3f} {0[1]:3n}\n'.format(a[i,:]) #:后面代表输出格式<代表左对齐,\n代表换行
  # {}内部的数字代表匹配变量的索引
  # :后面的格式有 整数n/d,浮点数f/F,科学计数法e/E,字符串s
f.close()

输出numpy结构化数组到txt文本

import numpy as np
a = np.random.rand((10,3))
b = np.rec.array(a.tolist(),dtype={'names':('id','argv','note'), 'formats':('int','float','U5')})
f = open("out.txt",'w')
for i in range(b.shape[0]):
  f.write('{0:<2n} {1:5.2f} {2}\n'.format(np.int(b[i,0].astype('float')),b[i,1].astype('float'),b[i,2]) 
f.close()

摘自官方文档https://docs.python.org/zh-cn/3/library/string.html?highlight=format#string.Formatter.format

posted @   Philbert  阅读(713)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
点击右上角即可分享
微信分享提示