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 スレッドを確認してください)。

それを知って、メソッドに戻りましょう.format

2 つのwhatthings.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 に答える