Aligning multiple columns in python 3

2019-08-31 07:05发布

I am trying to format a group of columns in python 3. So far I have not had much luck.

This is the code I am using.

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条回答
神经病院院长
2楼-- · 2019-08-31 07:49

Instead of using tabs to try and align things, specify the actual width of each column in your format statement.

Something like this:

print('{:20s} {:20s} {:20s}'.format(a,b,c))
查看更多
叼着烟拽天下
3楼-- · 2019-08-31 07:51

Tabs are not a great way to line columns up. Use fixed widths instead:

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

Note that I included the : colon in the string format; no need to pass in those colons with the lists.

You could make the width dynamic here; calculate it from the widest value in the r1 list for example:

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))

Here label_width is first interpolated into the {lwidth} slot, setting the width when formatting the {label:..} slot, etc. I used named slots rather than positional, because using proper names makes it easier to figure out what goes where.

查看更多
登录 后发表回答