【问题标题】:Python list comprehension using a class variable throws NameError [duplicate]使用类变量的 Python 列表理解抛出 NameError [重复]
【发布时间】:2015-11-28 22:53:14
【问题描述】:

我想使用另一个类变量将 dict 构造为类变量。 这确实在循环中工作(参见下面的order1),但在dict comprehension 中不起作用(参见下面的order2)。我收到一条错误消息,指出未定义 choices

然而,列表推导确实有效(参见order3),但这不是我想要的。 编辑:事实上,order3 也给出了一个错误,但在调用时,而不是在定义时,因为它定义了一个生成器对象,而不是一个列表。

class Foo():
    ALICE = 'TXT42'
    BOB = 'TXT4711'
    CHARLIE = 'TXT23'

    # List of lists for usage in a Django ChoiceField
    choices = (
        (ALICE, 'Alice'),
        (BOB, 'Bob'),
        (CHARLIE, 'Charlie'),
    )

    # Now I want to define an order for my constants in a dict, with
    # order[ALICE] < order[BOB] < order[CHARLIE]

    # This works, but is clumsy
    order1 = {}
    for i in range(len(choices)):
        order1[choices[i][0]] = i

    # This gives an error (but works if 'choices' is global):
    # "NameError: global name 'choices' is not defined"
    order2 = { choices[i][0]: i for i in range(len(choices)) }

    # This gives a list of dicts, not a dict (but doesn't throw an error)
    # My mistake: it gives a generator object. It will throw the same
    # error, if you try to access it or make it a list, 
    # e.g. order3 = list(...)
    order3 = ( { choices[i][0]: i } for i in range(len(choices)) )

当我在函数定义而不是类中尝试整个代码时,没有错误。当choices 确实是一个全局变量时它也可以工作,但当它是一个类变量时则不行。

显然,在类变量的上下文中,列表推导和字典推导的可能性存在细微差别。我现在认为这是一个错误,但请随意给出另一种解释。

尝试的 Python 版本:Debian GNU/Linux 下的 2.7.10 和 3.4.3


编辑:感谢@BrenBarn 找到了我没有找到的副本。它解释了我在这里遇到的问题。这不是错误,但也不是真正的功能。 ;-)

【问题讨论】:

    标签: python class scope list-comprehension


    【解决方案1】:

    此词典理解将适合您的需求:

    order2 = {choice[0]: idx for idx, choice in enumerate(choices)}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-04
      • 2014-02-03
      • 1970-01-01
      • 2014-05-12
      • 2015-11-28
      • 2021-08-02
      • 2011-06-15
      • 2014-05-06
      相关资源
      最近更新 更多