2014-11-30 3 views
1

파이썬 3에서 열 그룹을 포맷하려고합니다. 지금까지별로 운이 없었습니다. 나는 인쇄 할 기둥을 얻을 수 있었지만 그 기둥들을 일렬로 세울 수는 없었습니다. 다른 정보를 인쇄해야하는 경우 적응할 수 있도록 각 열을 동적으로 만들려고합니다. 그러나 열 서식에서 변수를 사용하려고하기 때문에 키 오류가 계속 발생합니다. 어떻게하면이 문제를 해결할 수 있을지 생각해? 열을 형식화 할 때 키 오류가 발생했습니다. 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)) 

답변

0

"{whatever}".format(whatever) 

를 사용하면 format 기능은 인터프리터를 들어 format(whatever)어떤"{whatever}"어떤을 "연결", "일치"또는 방법을 알고하지 않습니다 그들은 서로 관련이 없습니다. .format 함수에 "{whatever}"이 표시되면 키워드 인수 whatever을 호출하려고 시도하지만 아무 것도 없습니다. 그것은 단지 위치 인수가 있음을 알고 (하지 않은 드로이드 ... 음 ... 인수 그것은을 찾고 있음)

당신은 위치 인수가 키워드 인자에 비해 무엇인지 이해 할 수 있습니다

(체크 this SO 스레드) 일반적으로, 여러분이 작업하는 파이썬 개발에 대해서는 그 차이점을 잘 알아야합니다.

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

어쩌면 그것은 수행하여 명확이다 : 당신은 명시 적으로 .format 방법을 두 whatevers 사이의 연결 말할 필요

: 그것을 알고

,의는 .format 방법으로 돌아 가자

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). 그것은 당신에게 몇 가지 대안 아이디어를 줄 수 있습니다.