dict理解中的Python作用域 [英] Python scoping in dict comprehension

查看:171
本文介绍了dict理解中的Python作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> x = 'foo'
>>> {0: locals().get('x')}
{0: 'foo'}
>>> {0: locals().get('x' + spam) for spam in ['']}
{0: None}

这种行为差异的原因是什么?

解决方案

Dict理解和生成器理解会创建自己的局部范围.列表推导在Python 2.x中不是,但在Python 3中却是.(请注意,您的第一个示例不是dict推导.它只是一个文字dict,碰巧有一个表达式作为键0的值.)

>>> x = 'foo'
>>> {0: locals().get('x')}
{0: 'foo'}
>>> {0: locals().get('x' + spam) for spam in ['']}
{0: None}

What is the reason for this discrepancy in behaviour?

解决方案

Dict comprehensions and generator comprehensions create their own local scope. List comprehensions do not in Python 2.x, but do in Python 3. (Note that your first example is not a dict comprehension. It's just a literal dict that happens to have an expression as the value for the key 0.)

这篇关于dict理解中的Python作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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