[英]define a dict of variables in a for loop : hello = var('hello')
var = {'hello': 'world', 'good': 'day', 'see': 'you'}
Function: 功能:
def func(key):
return newfunc(var[key])
I would like to get something like this: hello = func('hello') = newfunc('world')
. 我想得到这样的东西:
hello = func('hello') = newfunc('world')
。
varlist = list(var.keys())
for i, variab in enumerate(varlist):
varname = variab
variab = func(varname)
But the problem at last the variables are not defined because the variable variab
is overwritten when the next iteration starts. 但是最后没有定义变量的问题,因为在下一次迭代开始时变量
variab
被覆盖。 So do I have other ways to code a for
loop to define all the variables in the dict? 那么,我还有其他方法可以为
for
循环编写代码以定义dict中的所有变量吗?
I know I can keep writing hello = func('hello')
and other variables every line but I would like to know if another method is possible. 我知道我可以继续在每一行写
hello = func('hello')
和其他变量,但是我想知道是否可以使用其他方法。
You may find this article to be a worthwhile read: http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html/ 您可能会发现这篇文章值得一读: http : //stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html/
The short answer to the problem is that when you do: 这个问题的简短答案是,当您这样做时:
variab = func(varname)
You aren't defining a new variable, you are just defining the value stored in the variable. 您不是在定义新变量,而是在定义存储在变量中的值。
Variab
is static. Variab
是静态的。 The name isnt changing. 名称没有改变。 To define a static variable, you use the syntax
要定义静态变量,请使用以下语法
globlas()[variablename] = variablevalue
And while this is possible, it begs the question of why? 虽然这是可能的,但却引出了为什么的问题? There is pretty much no need to create variables dynamically in this way, and there's a reason why you don't generally see this pattern in programming.
几乎没有必要以这种方式动态创建变量,这是为什么您在编程中通常看不到这种模式的原因。 The solution?
解决方案? Use a data structure to solve the problem properly.
使用数据结构正确解决问题。
The article suggests dictionaries, but depending on your data structure you can use classes as well. 本文建议使用字典,但是根据您的数据结构,您也可以使用类。 It depends on the problem you are trying to accomplish.
这取决于您要解决的问题。
If you must use dynamically created global variables I would strongly recommend getting past the new to Python
stage before doing so. 如果必须使用动态创建的全局变量,我强烈建议您在
new to Python
之前的new to Python
阶段。 Again, the current code patterns and data structures exist for a reason, and I would discourage willingly avoiding them in favor of a workaround style solution. 同样,当前的代码模式和数据结构存在是有原因的,因此我会劝阻他们避免使用有利于变通方法的解决方案。
Dynamically creating variables can be done, but it is not wise. 可以动态创建变量,但这并不明智。 Maintenance is a nightmare.
维护是一场噩梦。 It would be better to store the functions in a dictionary with the key value being what the dynamically created variable would have been.
最好将函数存储在字典中,而键值应为动态创建的变量本应具有的值。 This should give you an idea of how it can be done:
这应该使您了解如何完成此操作:
#!/usr/bin/python
h = {'hello': 'world', 'good': 'day', 'see': 'you' }
def func(v):
def newfunc():
return v
return newfunc
for k,v in h.items():
h[k] = func(v)
a = h['hello']()
b = h['good']()
c = h['see']()
print("a = {}".format(a))
print("b = {}".format(b))
print("c = {}".format(c))
First of all, are those values callable functions or just string values? 首先,这些值是可调用的函数还是仅仅是字符串值?
If they are some callable functions, something like: 如果它们是一些可调用的函数,则类似于:
a = {'hello': hello, 'world': world}
It is simple and straight forward: 这很简单明了:
A = {'hello': hello, 'world': world}
def foo(var):
callback = A.get(var, None)
# You cancheck and raise when the value
# is not a method.
if not callable(callback):
raise
return callback
foo('hello')
You can put the variable, fn pairs in a dict. 您可以将变量fn对放入字典中。 Also some comments:
还有一些评论:
varlist = list(var.keys())
line, you can just use for variab in var.keys()
... varlist = list(var.keys())
行,您只需for variab in var.keys()
... var.keys()
. var.keys()
。 for key in dictionary
iterates through the keys of the dictionary, so you can just use for variab in var
. for key in dictionary
会迭代for key in dictionary
的key,因此您可以for variab in var
使用for variab in var
。 So something like this would work: fn_dict = {} for varname in var: fn_dict[varname] = func(varname)
因此,这样的方法将起作用:
fn_dict = {} for varname in var: fn_dict[varname] = func(varname)
At the end of the loop you will have the fn_dict populated with the key, function pairs you want. 在循环的最后,您将使用所需的键,函数对填充fn_dict。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.