为什么008和009 Python Python的无效键? [英] Why are 008 and 009 invalid keys for Python dicts?

查看:101
本文介绍了为什么008和009 Python Python的无效键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能将008或009作为Python dict的键,但001-007是否正常?
示例:

  some_dict = {
001:spam,
002:鸡蛋,
003:foo,
004:bar,
008:anything,#抛出一个SyntaxError
009:nothing#抛出一个SyntaxError
}

更新:问题解决。我没有意识到开始一个零的字面值使它八进制。这似乎很奇怪为什么零?

解决方案

在python和其他一些语言中,如果您使用0启动一个数字,则该数字被解释为八进制基数8),其中只有0-7是有效数字。您必须将代码更改为:

  some_dict = {
1:spam,
2:egg,
3:foo,
4:bar,
8:anything,
9:nothing}

或者如果前导零是非常重要的,请使用字符串进行密钥。


Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example:

some_dict = {
    001: "spam",
    002: "eggs",
    003: "foo",
    004: "bar",
    008: "anything", # Throws a SyntaxError
    009: "nothing"   # Throws a SyntaxError
    }

Update: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero?

解决方案

In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where only 0-7 are valid digits. You'll have to change your code to this:

some_dict = { 
    1: "spam",
    2: "eggs",
    3: "foo",
    4: "bar",
    8: "anything",
    9: "nothing" }

Or if the leading zeros are really important, use strings for the keys.

这篇关于为什么008和009 Python Python的无效键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆