我正在尝试在 python 3 中格式化一组列。到目前为止,我运气不佳。我设法让列打印,但我不能让他们排队。我正在尝试使每一列动态化,以便在需要打印不同信息时进行调整。但是因为我试图在列格式中使用变量,所以我不断收到关键错误。知道如何解决这个问题吗?
Indicator :Min :Max
----------------------------------------------------------------------------
Traceback (most recent call last):
File "G:/test.py", line 154, in <module>
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 ))
KeyError: 'heart'
这是我正在使用的代码。
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 ))