尝试使用变量python 3格式化列时出现键错误

2024-09-28 21:49:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python3格式化一组列。到目前为止我运气不太好。我设法把专栏打印出来,但我没办法把它们排成一行。我试图使每一列都是动态的,以便在需要打印不同的信息时能够进行调整。但是因为我试图在列格式中使用变量,所以我一直得到关键错误。你知道我怎么解决这个问题吗?在

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'

这是我使用的代码。在

^{pr2}$

Tags: 信息动态colwidthsmokepython3办法motor
1条回答
网友
1楼 · 发布于 2024-09-28 21:49:15

当你使用

"{whatever}".format(whatever)

format函数不知道如何将"{whatever}"中的任何format(whatever)中的whatever进行“匹配”或“连接”,对于解释器来说,它们之间没有任何关系。当.format函数看到"{whatever}"时,它将尝试在其调用中查找一个关键字参数whatever,但没有。它只知道存在一个位置参数(这不是droid。。。呃。。。它正在寻找的论点)

您可能想了解位置参数与关键字参数(checkthisSO thread)的区别,一般来说,您需要非常清楚地了解您所从事的任何Python开发的区别。在

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

您需要显式地告诉.format方法这两个whatever之间的联系:

^{pr2}$

或许这样做会更清楚:

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

检查这个string formatting tutorial(尤其是它的examples section)。它可能会给你一些另类的想法。在

相关问题 更多 >