我想在Python中动态创建变量。有人有什么创造性的方法吗?


当前回答

使用exec()方法运行任意代码。例如,假设你有一个字典,你想把每个键转换成一个具有其原始字典值的变量,你可以这样做:

>>> c = {"one": 1, "two": 2}
>>> for k, v in c.items():
...     exec(f"{k} = {v}")
... 
>>> one
1
>>> two
2

其他回答

除非非常需要创建一堆变量名,否则我会使用字典,在字典中您可以动态地创建键名并将值关联到每个键名。

a = {}
k = 0
while k < 10:
    # dynamically create key
    key = ...
    # calculate value
    value = ...
    a[key] = value 
    k += 1

collections模块中还有一些有趣的数据结构可能适用。

使用exec()方法运行任意代码。例如,假设你有一个字典,你想把每个键转换成一个具有其原始字典值的变量,你可以这样做:

>>> c = {"one": 1, "two": 2}
>>> for k, v in c.items():
...     exec(f"{k} = {v}")
... 
>>> one
1
>>> two
2

关键字参数允许将变量从一个函数传递到另一个函数。通过这种方式,您可以使用字典的键作为变量名(可以在while循环中填充)。当它被调用时,字典名只需要在前面加上**。

# create a dictionary
>>> kwargs = {}
# add a key of name and assign it a value, later we'll use this key as a variable
>>> kwargs['name'] = 'python'

# an example function to use the variable
>>> def print_name(name):
...   print name

# call the example function
>>> print_name(**kwargs)
python

没有**,kwargs只是一个字典:

>>> print_name(kwargs)
{'name': 'python'}
vars()['meta_anio_2012'] = 'translate'

在全局和/或本地名称空间中填充内容并不是一个好主意。使用字典太像其他语言了……D ['constant-key'] = value看起来很尴尬。Python是面向对象的。用一位大师的话来说:“命名空间是一个非常棒的想法——让我们做更多这样的事情吧!”""

是这样的:

>>> class Record(object):
...     pass
...
>>> r = Record()
>>> r.foo = 'oof'
>>> setattr(r, 'bar', 'rab')
>>> r.foo
'oof'
>>> r.bar
'rab'
>>> names = 'id description price'.split()
>>> values = [666, 'duct tape', 3.45]
>>> s = Record()
>>> for name, value in zip(names, values):
...     setattr(s, name, value)
...
>>> s.__dict__ # If you are suffering from dict withdrawal symptoms
{'price': 3.45, 'id': 666, 'description': 'duct tape'}
>>>