下面的代码
class Foo:
bar=[sum( i^j for i in range(9) )for j in range(9)]
加注
NameError: global name 'j' is not defined
在我的 Python 2.7.14 IDLE 以及在线解释器上。
如果我理解正确,sum 接受可迭代作为输入。 出了什么问题?
附言。
- 如果我改用
sum([ ... ])就不会出现错误。 - 如果我删除外部列表,将不会出现错误。
- 如果第二行在类外执行,则不会出错。
- Python3(尤其是我的 3.4.2 IDLE)不会引发错误。
请您参考如下方法:
看起来这是一个 known issue使用 Python 2:
In Python 2, list comprehensions don't have their own scope, so the x in your initial example lives at class scope. However, the set comprehension does have its own scope. By design, a variable defined at class scope is not visible to inner scopes inside that class.
In Python 3, this works because the list comprehension has its own scope.
给出的例子是:
class Sudoku(dict):
COLUMNS = [
{(x, y) for y in xrange(9)} for x in xrange(9)}
]
