1

我正在尝试在 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 ))
4

1 回答 1

0

当你使用

"{whatever}".format(whatever)

format函数不知道如何将任何内容“匹配”或“连接”到解释器中的任何内容。对于解释器,它们彼此无关。当函数看到它时,它将尝试在其调用中查找关键字参数,但没有。它只知道有一个位置参数(这不是机器人......呃......它正在寻找的参数)"{whatever}"format(whatever).format"{whatever}"whatever

您可能想了解位置参数与关键字参数的区别(检查SO 线程) 一般来说,对于您从事的任何 Python 开发,您都需要非常了解这种差异。

知道了,让我们回到.format方法:

您需要明确地告诉.format方法这两个之间的联系

"{whatever}".format(whatever=whatever)

也许这样做会更清楚:

foo="hello"
"{whatever}".format(whatever=foo)
#   ^                 ^
#   |_________________|

所以在你的情况下,你可以这样做:

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=heart, heart_col_width=heart_col_width,
            motor=motor, motor_col_width=motor_col_width,
            teen=teen, teen_col_width=teen_col_width,
            smoke=smoke, smoke_col_width=smoke_col_width,
            obese=obese, obese_col_width=obese_col_width)
    )

由于使用了这些关键字参数,如果所有列的列宽相同,则无需重新指定。您可以在字符串的不同部分重用它们:

heart = "hello"
motor = "goodbye"
filler = 10
print (
    "{heart:{filler}} someting something {motor:{filler}} something something"
    .format(heart=heart, motor=motor, filler=filler)
)

检查这个字符串格式化教程(特别是它的示例部分)。它可能会给你一些替代的想法。

于 2014-11-30T22:58:03.553 回答