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

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

问题描述

我发现在运行时能够创建新变量非常有用,然后创建一个后续处理结果字典,即写入一个文件:



<$ p $对于我在范围(1,10)中的i $ p
temp =variable+ str(i)
vars()[temp] = myFunctionThatReturnsData()#variable1 = data1,variable2 = data2等。
myDict [temp] = vars(temp)

创建字典条目[result1: data1]我可以用myDict [result1]调用。我一直在使用vars(),而没有真正理解我在做什么。我拿它 vars()返回带有局部变量(?)的字典,而


vars()[x] = y


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



我有一个脚本,我通过一个使用{input1:data1,input2:data2}编写的字典,我使用这种方法遍历所有的值,存储所有的结果,并将其输出到一个文件。这个代码位于一个类内的函数中,并且正在工作。



我的困惑之处在于,我已经阅读了关于本地人()不应该被弄乱的各种帖子,以及vars()如何等同于当地人()或全局变量()..



所以我的问题是(至少)两重:



1.什么是vars(),特别是vars()[x] = y do,



2.这个字典的范围是什么我需要记住,我写更大的程序



3.这是一个很好的编程习惯。



感谢提前!

解决方案

创建变量序列的pythonic方式



如果您想要一系列变量,请创建一个序列,而不是尝试创建独立变量,如:

 code> variable0 
variable1
variable2
variable3

你应该看看创建一个列表,这与S.Lott建议的(SL ott通常有很好的建议),但是更精确地映射到循环:

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

(请注意,我们放弃循环变量( _ )。我们只是试图获得10次通行证。)



然后您的数据将可用:

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

作为额外的好处,您可以:

 依次为基准:
process_data(datum)

起初,你可能会让你的序列从0开始。你可以通过各种扭曲来使你的实际数据从1开始,但是比它的价值更痛苦。我建议刚刚习惯使用零基列表。一切都是围绕着它们建立起来的,而且它们很快就开始感觉到自然。



vars()和locals()



现在,回答你的问题的另一部分。 vars()(或 localals())提供了对由python创建的变量的低级访问。因此,以下两行是等价的。

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

vars()['x'] x 的范围完全相同。 locals()(或 vars())的一个问题是它会让你把东西放在命名空间中你不能通过正常的方式离开命名空间。所以你可以这样做: localals()[4] ='一个整数',但是不能再次使用本地人,因为本地命名空间(与所有python命名空间一样)仅用于保存字符串。

 >>> x = 5 
>>>> dir()
['__builtins__','__doc__','__name__','x']
>>> locals()[4] ='整数'
>>> dir()
[4,'__builtins__','__doc__','__name__','x']
>>> x
5
>>> 4
4
>>>本地人()[4]
'整数'

请注意,4不返回与本地人()[4]相同的事情。这可能会导致一些意想不到的难以调试的问题。这是避免使用 localals()的一个原因。另一个原因是,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天全站免登陆