打印漂亮的文本列和浮动(抑制小数字)

2024-09-30 02:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我们能从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.        -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_printoptions(precision=5,suppress=True)print(array)的浮点结构,但是我不知道如何将文本放到左边,最好去掉括号。你知道吗


Tags: 字符串文本数字数组浮点text1text2text4
1条回答
网友
1楼 · 发布于 2024-09-30 02:26:07

在花了比预期更多的时间之后,我有了一个程序解决方案,我选择了完全抑制零。你知道吗

你知道吗脚本.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)

Python3脚本.py你知道吗

dkl             0.26212     0.10060     0.62061
dofj          200.00000   200.38320      -     
ldfj           10.40011     0.23930     0.00959
gasf            0.03731      -       1000.80968

相关问题 更多 >

    热门问题