2011-10-17 5 views
1

Possible Duplicate:
Is there any reason why lVals = [1, 08, 2011] throws an exception?이 사전 정의가 구문 오류를 발생시키는 이유는 무엇입니까?

나는 각자의 단어에 요일 번호를 매핑하는 사전을 정의하고 있습니다.

: 아래의 코드와 같이 오류를 중지 08 및 09이 될 것을 98 99 있도록 코드를 수정하고 하이라이트 "08"

days = {01:"first", 02:"second", 03:"third", 04:"fourth", 05:"fifth", 06:"sixth", 07:"seventh", 08:"eighth", 09:"nineth", 10:"tenth", 
    11:"eleventh", 12:"twelvth", 13:"thirteenth", 14:"fourteenth", 15:"fifteenth", 16:"sixteenth", 17:"seventeenth", 18:"eighteenth", 
    19:"nineteenth", 20:"twentieth", 21:"twenty-first", 22:"twenty-second", 23:"twenty-third", 24:"twenty-fourth", 25:"twenty-fifth", 
    26:"twenty-sixth", 27:"twenty-seventh", 28:"twenty-eighth", 29:"twenty-nineth", 30:"thirtieth", 31:"thirty-first"} 

: 몇 가지 이유를 들어 다음 코드는 "유효하지 않은 토큰 구문 에러를"제기

days = {01:"first", 02:"second", 03:"third", 04:"fourth", 05:"fifth", 06:"sixth", 07:"seventh", 98:"eighth", 99:"nineth", 10:"tenth", 
    11:"eleventh", 12:"twelvth", 13:"thirteenth", 14:"fourteenth", 15:"fifteenth", 16:"sixteenth", 17:"seventeenth", 18:"eighteenth", 
    19:"nineteenth", 20:"twentieth", 21:"twenty-first", 22:"twenty-second", 23:"twenty-third", 24:"twenty-fourth", 25:"twenty-fifth", 
    26:"twenty-sixth", 27:"twenty-seventh", 28:"twenty-eighth", 29:"twenty-nineth", 30:"thirtieth", 31:"thirty-first"} 

은 출력이된다 :

{1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'fifth', 6: 'sixth', 7: 'seventh', 10: 'tenth', 11: 'eleventh', 12: 'twelvth', 13: 'thirteenth', 14: 'fourteenth', 15: 'fifteenth', 16: 'sixteenth', 17: 'seventeenth', 18: 'eighteenth', 19: 'nineteenth', 20: 'twentieth', 21: 'twenty-first', 22: 'twenty-second', 23: 'twenty-third', 24: 'twenty-fourth', 25: 'twenty-fifth', 26: 'twenty-sixth', 27: 'twenty-seventh', 28: 'twenty-eighth', 29: 'twenty-nineth', 30: 'thirtieth', 31: 'thirty-first', 98: 'eighth', 99: 'nineth'} 

이전에 잘못된 키 사전의 끝으로 이동했다. 여기에 무슨 일이 일어나고 있는지 명소 사람에게

많은 감사,

제임스

답변

9

는 수 0는 파이썬에서 8 진수는 것을 나타내는 정수 리터럴에 접두사입니다.

실수로 생략으로

..., 그래서 친절하게 자신의 의견에서 지적 @larsmans로, 07을 통해 단지 숫자를 포함 89 제외에 수를 제한합니다.

참고로이 구문은 Python 2.x의 구문입니다.이 코드는 Python 3.0에서 변경되었으므로 여기에 온 정확한 이유가 있습니다. PEP 3127에는 변경 내용이 자세히 나와 있습니다.

가장 중요한 비트 : 파이썬

Almost all currently popular computer languages, including C/C++, Java, Perl, and JavaScript, treat a sequence of digits with a leading zero as an octal number. Proponents of treating these numbers as decimal instead have a very valid point -- [...] the entire non-computer world uses decimal numbers almost exclusively.

+0

... 분명히 '08'은 유효한 8 진수가 아닙니다. +1. –

1

하는 0와 숫자는 접두어 인 진수로 나타낸다. 따라서 및 9 숫자가 8 진수로 존재하지 않으므로 0809은 오류를 발생시킵니다. 그냥 0을 없애면 효과가 있습니다.

1

0으로 시작하고 숫자 만 포함하는 숫자는 octal으로 해석됩니다. 8과 9는 유효한 8 진수가 아닙니다. 08과 09를 8과 9로 바꾸면 코드가 작동합니다.

관련 문제