Python:使用 vars() 将字符串分配给变量 [英] Python: Using vars() to assign a string to a variable

查看:28
本文介绍了Python:使用 vars() 将字符串分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现能够在运行时创建新变量并创建结果字典以供稍后处理(即写入文件)非常有用:

myDict = {}对于范围内的 i (1,10):temp = "变量"+str(i)vars()[temp] = myFunctionThatReturnsData() # variable1= data1, variable2 = data2, etc.myDict[temp] = vars(temp)

它创建了字典条目 [result1:data1],我可以用 myDict[result1] 调用它.我一直在使用 vars() 并没有真正理解我在做什么.我认为 vars() 返回一个包含局部变量 (?) 的字典,并且

<块引用>

vars()[x] = y

创建一个新的 [x:y] 字典条目?

我有一个脚本,我传入一个用 {input1:data1,input2:data2} 准备的字典,我使用这个方法遍历所有值,存储所有结果,并将其输出到文件中.这段代码位于类中的函数内,并且正在运行.

我感到困惑的根源是我已经阅读了关于如何不应该混淆 locals() 以及 vars() 如何等效 (?) 到 locals() 或 globals() 的各种帖子.

所以我的问题(至少)有两个方面:

1.vars() 究竟做了什么,特别是 vars()[x] = y 做了什么,

2.这本字典的范围是什么(我在编写更大的程序时需要记住什么

3.这是否是良好的编程习惯.

提前致谢!

解决方案

pythonic 方法来创建变量序列

如果您想要一个变量序列,请创建一个序列.而不是尝试创建自变量,例如:

变量0变量1变量2变量3

您应该考虑创建一个list.这类似于 S.Lott 的建议(S.Lott 通常有很好的建议),但更巧妙地映射到您的 for 循环:

sequence = []对于 xrange(10) 中的 _:序列.追加(function_that_returns_data())

(注意我们丢弃了循环变量(_).我们只是想获得 10 次通过.)

然后您的数据将可用:

序列[0]序列[1]序列[2]序列[3][...]序列[9]

作为额外的奖励,您可以:

 用于数据顺序:过程数据(数据)

起初,您可能会因为序列从 0 开始而抽搐.您可以通过各种扭曲使实际数据从 1 开始,但这样做的痛苦比值得的要多.我建议您习惯于使用基于零的列表.一切都是围绕着他们建立的,他们很快就会感觉很自然.

vars() 和 locals()

现在,回答您问题的另一部分.vars()(或locals())提供对python创建的变量的低级访问.因此下面两行是等价的.

locals()['x'] = 4x = 4

vars()['x'] 的作用域与 x 的作用域完全相同.locals()(或vars())的一个问题是它会让你把一些东西放在命名空间中,而这些东西是你无法通过正常方式从命名空间中取出来的.所以你可以做这样的事情:locals()[4] = 'An integer',但是如果不再次使用 locals,你就无法恢复它,因为本地命名空间(与所有 python 一样)命名空间)仅用于保存字符串.

<预><代码>>>>x = 5>>>目录()['__builtins__', '__doc__', '__name__', 'x']>>>locals()[4] = '一个整数'>>>目录()[4, '__builtins__', '__doc__', '__name__', 'x']>>>X5>>>44>>>当地人()[4]'一个整数'

请注意,4 返回的内容与 locals()[4] 不同.这可能会导致一些意想不到的、难以调试的问题.这是避免使用 locals() 的原因之一.另一个原因是,仅仅执行 Python 提供的更简单、更不容易出错的方法(例如创建变量序列)通常会很复杂.

I find it very useful to be able to create new variables during runtime and create a dictionary of the results for processing later, i.e. writing to a file:

myDict = {}
for i in range (1,10):
    temp = "variable"+str(i) 
    vars()[temp] = myFunctionThatReturnsData() # variable1= data1, variable2 = data2,etc.
    myDict[temp] = vars(temp)

which creates the dictionary entry [result1:data1] which i can call with myDict[result1]. I have been using vars() without really understanding what I'm doing. I take it vars() returns a dictionary with the local variables(?), and

vars()[x] = y

creates a new dictionary entry of [x:y] ?

I have a script where I pass in a dictionary prepared with {input1:data1,input2:data2}, and i use this method to iterate through all the values, store all the results, and output it to a file. This bit of code is inside a function within a class, and is working.

My source of confusion is that I have read various posts on how locals() shouldn't be messed with, and how vars() is equivalent(?) to locals(), or globals()..

So my question is (at least) two-fold:

1.What exactly does vars(),or in particular, vars()[x] = y do,

2.What the scope of this dictionary is (what I need to keep in mind as I write bigger programs

3.Whether this is good programming practice.

Thanks in advance!

解决方案

The pythonic way to create a sequence of variables

If you want a sequence of variables, create a sequence. Instead of trying to create independent variables like:

variable0
variable1
variable2
variable3

You should look at creating a list. This is similar to what S.Lott is suggesting (S.Lott usually has good advice), but maps more neatly onto your for loop:

sequence = []
for _ in xrange(10):
    sequence.append(function_that_returns_data())

(Notice that we discard the loop variable (_). We're just trying to get 10 passes.)

Then your data will be available as:

sequence[0]
sequence[1]
sequence[2]
sequence[3]
[...]
sequence[9]

As an added bonus, you can do:

for datum in sequence:
    process_data(datum)

At first, you may twitch at having your sequence start at 0. You can go through various contortions to have your actual data start at 1, but it's more pain than it's worth. I recommend just getting used to having zero-based lists. Everything is built around them, and they start to feel natural pretty quickly.

vars() and locals()

Now, to answer another part of your question. vars() (or locals()) provides low level access to variables created by python. Thus the following two lines are equivalent.

locals()['x'] = 4
x = 4

The scope of vars()['x'] is exactly the same as the scope of x. One problem with locals() (or vars()) is that it will let you put stuff in the namespace that you can't get out of the namespace by normal means. So you can do something like this: locals()[4] = 'An integer', but you can't get that back out without using locals again, because the local namespace (as with all python namespaces) is only meant to hold strings.

>>> x = 5
>>> dir()
['__builtins__', '__doc__', '__name__', 'x']
>>> locals()[4] = 'An integer'
>>> dir()
[4, '__builtins__', '__doc__', '__name__', 'x']
>>> x
5
>>> 4
4
>>> locals()[4]
'An integer'

Note that 4 does not return the same thing as locals()[4]. This can lead to some unexpected, difficult to debug problems. This is one reason to avoid using locals(). Another is that it's generally a lot of complication just to do things that python provides simpler, less error prone ways of doing (like creating a sequence of variables).

这篇关于Python:使用 vars() 将字符串分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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