Python 打印漂亮的文本列和浮动(抑制小数字)
我们可以从python获得如下输出吗Python 打印漂亮的文本列和浮动(抑制小数字),python,python-3.x,numpy,printing,Python,Python 3.x,Numpy,Printing,我们可以从python获得如下输出吗 text1 -9.98442 -10. -0.01558 text2 -0. -0. 0. text3 0. -0. -0. text4 0.24829 0.24829 -0. text5 -7.40799 -7.40575 0.00224 text6 0. -0.
text1 -9.98442 -10. -0.01558
text2 -0. -0. 0.
text3 0. -0. -0.
text4 0.24829 0.24829 -0.
text5 -7.40799 -7.40575 0.00224
text6 0. -0. -0.
text7 -0. 0. 0.
text8 -5.88917 -5.83199 0.05718
text9 -0. 0. 0.
text10 -6.83455 -6.74592 0.08862
即左侧的文本,以及周期对齐的列,其中抑制的小数字(例如,来自一维字符串数组和二维浮点数组)
Numpy可以使用
np.set\u printoptions(精度=5,抑制=True)
和print(数组)
生成浮点结构,但我不知道如何将文本移到左边,最好去掉括号 在花费了比预期更多的时间之后,我有了一个编程解决方案,我选择了完全抑制零
script.py:
import numpy as np
def printskip(text,mat,tol=5,off=6):
rows = np.size(mat,0)
cols = np.size(mat,1)
lim = 10**(-tol)
zero = ' '*off+'-'+' '*tol
form = ':>'+str(off+tol+1)+'.'+str(tol)+'f}'
for row in range(rows):
textform=''
for i in range(cols):
if abs(mat[row,i]) < lim:
txtf = zero
else:
txtf = '{'+str(i)+form
textform += txtf
print('{:<10}'.format(text[row]),textform.format(*mat[row,:]))
text = ['dkl', 'dofj', 'ldfj','gasf']
dat = np.array([
[0.2621206 , 0.1006 , 0.620606],
[200.0000005 , 200.3832 , 0.062532e-7],
[10.4001095 , 0.2393 , 0.009593],
[0.0373096 , 1.e-7 , 1000.809681]
])
printskip(text,dat,5)
看看下面的例子。
制表
软件包可以满足您的需要。也许您也应该看看。这个库提供了一个DataFrame模型,这是处理类似表的数据的一个很好的方法。@jpp这些答案不会抑制小数字,这是这里的要点,否则我可以使用string.format()
@JonatanÖström,这很公平。请给你的问题加一个更合适的标题好吗?@Georgy我知道你是对的,但是通读人们失败的尝试真的很无聊,我试着提到numpy
输出。
dkl 0.26212 0.10060 0.62061
dofj 200.00000 200.38320 -
ldfj 10.40011 0.23930 0.00959
gasf 0.03731 - 1000.80968