我想在Python中动态创建变量。有人有什么创造性的方法吗?
当前回答
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'}
>>>
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}
使用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模块中还有一些有趣的数据结构可能适用。
vars()['meta_anio_2012'] = 'translate'
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录