python - 如何在Python中使用numpy.savetxt居中对齐不同长度的列?

标签 python format alignment output

我有几个列表,其中包含字符串和 float 作为其元素。

import numpy as num

COLUMN_1 = ['KIC 7742534', 'Variable Star of RR Lyr type' , 'V* V368 Lyr',
        'KIC 7742534', '4.0', '0.4564816']

COLUMN_2 = ['KIC 76', 'Variable Star' , 'V* V33 Lyr',
        'KIC 76', '5.0', '0.45']

DAT = num.column_stack((COLUMN_1, COLUMN_2))
num.savetxt('SAVETXT.txt', DAT, delimiter=' ', fmt='{:^10}'.format('%s'))

运行此文件时得到的输出如下:

KIC 7742534    ,    KIC 76    
Variable Star of RR Lyr type    ,    Variable Star    
V* V368 Lyr    ,    V* V33 Lyr    
KIC 7742534    ,    KIC 76    
4.0    ,    5.0    
0.4564816    ,    0.45     

理想的输出如下所示(包括对齐的标题)

#ELEMENT1                            ELEMENT2
KIC 7742534                     ,    KIC 76    
Variable Star of RR Lyr type    ,    Variable Star    
V* V368 Lyr                     ,    V* V33 Lyr    
KIC 7742534                     ,    KIC 76    
4.0                             ,    5.0    
0.4564816                       ,    0.45   

如果字符串没有定义最大宽度,我怎样才能得到这样的输出(带有对齐的标题)。我尝试过修改字符串的格式(fmt),但到目前为止还没有成功。

-谢谢!

最佳答案

您将需要计算输出(或输入,具体取决于您如何看待它)的最长行的最大字符串长度,该方法类似于

max_len = max(max(map(len,l)) for l in zip(COLUMN_1,COLUMN_2))

一定能实现。之后,您需要根据 max_len 的值动态更改 fmt 参数,您可以这样做:

fmt=('{:^%d}' % max_len).format('%s')

以下非 numpy 示例显示了预期的输出:

with open('ofile.txt','w+') as f:
    max_len = max(max(map(len,l)) for l in zip(COLUMN_1,COLUMN_2))
    for line in zip(COLUMN_1,COLUMN_2):
        f.write(','.join(('{:<%s}' % (max_len)).format(e) for e in line)+'\n')

生成一个文本文件ofile.txt,其中包含:

KIC 7742534                 ,KIC 76                      
Variable Star of RR Lyr type,Variable Star               
V* V368 Lyr                 ,V* V33 Lyr                  
KIC 7742534                 ,KIC 76                      
4.0                         ,5.0                         
0.4564816                   ,0.45          

关于python - 如何在Python中使用numpy.savetxt居中对齐不同长度的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16632360/

相关文章:

python - 如何将一串电子邮件地址排序到列表中

format - 在格式模块上配置更大的列数限制

c++ - 内存对齐和长拷贝

html - 行内显示留下空白

html - 右上角的日期导致页眉偏心

python - 在循环 python/pandas 中保存时不同的文件名

python - 无法使用python从Azure Key Vault获取 secret /证书| 'KeyVaultManagementClient' 对象没有属性 'get_secret'

python - 如何将 Spark Streaming 数据转换为 Spark DataFrame

c++ - sscanf_s 无法从字符串中找到所有值

c - 我将如何在 C 中编写自己的新格式说明符?