在字典理解中使用locals() [英] using locals() inside dictionary comprehension

查看:60
本文介绍了在字典理解中使用locals()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码不起作用,我认为是因为理解内的locals()变量将引用对其中的理解进行评估的嵌套块:

The following code doesn't work, I assume because the locals() variable inside the comprehension will refer to the nested block where comprehension is evaluated:

def f():
    a = 1
    b = 2
    list_ = ['a', 'b']
    dict_ = {x : locals()[x] for x in list_}

我可以改用globals(),它似乎可以工作,但这可能会带来一些其他问题(例如,如果周围范围中的某个变量碰巧具有相同的名称).

I could use globals() instead, and it seems to work, but that may come with some additional problems (e.g., if there was a variable from a surrounding scope that happens to have the same name).

在功能f的范围内,是否有任何东西可以使字典准确地使用变量?

Is there anything that would make the dictionary using the variables precisely in the scope of function f?

注意:之所以这样做,是因为我有很多变量希望稍后再放入字典中,但同时不想通过编写dict_['a']而不是a来使代码复杂化. /p>

Note: I am doing this because I have many variables that I'd like to put in a dictionary later, but don't want to complicate the code by writing dict_['a'] instead of a in the meantime.

推荐答案

您也许可以这样做:

def f(): 
    a = 1 
    b = 2 
    list_ = ['a', 'b'] 
    locals_ = locals()
    dict_ = dict((x, locals_[x]) for x in list_)

但是,我强烈建议不要将locals()用于此目的.

However, I would strongly discourage the use of locals() for this purpose.

这篇关于在字典理解中使用locals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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