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


当前回答

vars()['meta_anio_2012'] = 'translate'

其他回答

vars()['meta_anio_2012'] = 'translate'

关键字参数允许将变量从一个函数传递到另一个函数。通过这种方式,您可以使用字典的键作为变量名(可以在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'}

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

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

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

Globals()返回模块变量的字典。你可以通过在字典上创建一个键来创建一个新变量:

# By default, a module has some hidden variables defined
print({k: v for k, v in globals().items() if not k.startswith("__")})

for i in range(1, 11):
    globals()[f"my_variable_{i}"] = i

print()
print(my_variable_1)
print(my_variable_2)
# and so on

print()
print({k: v for k, v in globals().items() if not k.startswith("__")})

结果:

{}

1
2

{'i': 10, 'my_variable_1': 1, 'my_variable_2': 2, 'my_variable_3': 3, 'my_variable_4': 4, 'my_variable_5': 5, 'my_variable_6': 6, 'my_variable_7': 7, 'my_variable_8': 8, 'my_variable_9': 9, 'my_variable_10': 10}

在全局和/或本地名称空间中填充内容并不是一个好主意。使用字典太像其他语言了……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'}
>>>