我有几个列表,其中包含字符串和 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/