在python 3中对齐多个列

时间:2014-11-30 02:22:47

标签: python-3.x alignment multiple-columns

我正在尝试在python 3中格式化一组列。到目前为止,我没有太多运气。

这是我正在使用的代码。

first_row = ['Indicator',':Min',':Max']

col_width = max(len(word) for word in first_row) +20# padding

print ("".join(word.ljust(col_width) for word in first_row))

print('----------------------------------------------------------------------------')

heart=['Heart Disease Death Rate     (2007)',stateheart_min(),heartdis_min(),stateheart_max(),heartdis_max()]
motor=[ 'Motor Vehicle Death Rate     (2009)',statemotor_min(),motordeath_min(),statemotor_max(),motordeath_max()]
teen=['Teen Birth Rate (2009)',stateteen_min(),teenbirth_min(),stateteen_max(),teenbirth_max()]
smoke=['Adult Smoking     (2010)',statesmoke_min(),adultsmoke_min(),statesmoke_max(),adultsmoke_max()]
obese=['Adult Obesity     (2010)',stateobese_min(),adultobese_min(),stateobese_max(),adultobese_max()]

heart_col_width = max(len(word) for word in heart)
motor_col_width = max(len(word) for word in motor)
teen_col_width = max(len(word) for word in teen)
smoke_col_width = max(len(word) for word in smoke)
obese_col_width = max(len(word) for word in obese)


for heart, motor, teen, smoke, obese in zip(heart, motor, teen, smoke, obese ):
    print('{heart:{heart_col_width}}:{motor:{motor_col_width}} {teen:{teen_col_width}{smoke:    {smoke_col_width}}{obese:{obese_col_width}'.format(heart, motor, teen, smoke, obese ))

2 个答案:

答案 0 :(得分:2)

不要使用制表符来尝试对齐事物,而是在格式语句中指定每列的实际宽度。

这样的事情:

print('{:20s} {:20s} {:20s}'.format(a,b,c))

答案 1 :(得分:2)

标签不是排列列的好方法。请改用固定宽度:

for label, minimum, maximum, e, f in zip(r1, r3, r4, r5, r6):
    print('{:32}: {:20}: {:20}'.format(label, minimum, maximum))

请注意,我以字符串格式包含:冒号;不需要将这些冒号传递给列表。

你可以在这里使宽度动态;从r1列表中最宽的值计算它,例如:

label_width = max(len(v) for v in r1)
minimum_col_width = max(len(v) for v in r3)
maximum_col_width = max(len(v) for v in r4)

for label, minimum, maximum, e, f in zip(r1, r3, r4, r5, r6):
    print('{label:{lwidth}}: {min:{minwidth}}: {max:{maxwidth}}'.format(
        lwidth=label_width, minwidth=minimum_col_width, maxwidth=maximum_col_width,
        min=minimum, max=maximum))

此处label_width首先插入到{lwidth}插槽中,在格式化{label:..}插槽时设置宽度等。我使用命名插槽而不是位置,因为使用专有名称使其成为更容易弄清楚到底发生了什么。