在python循环中使用迭代器作为变量名 [英] Use iterator as variable name in python loop
问题描述
我一直想知道是否有办法在Python循环中使用迭代器作为变量名。例如,如果我想创建对象 v0
, v1
, v2
,有没有办法做这样的事情:
I've been wondering if there is a way to use an iterator as a variable name in a Python loop. For example, if I wanted to create objects v0
, v1
, v2
, is there a way to do something like this:
for i in range(3):
v + str(i) = i**2
我知道语法错误,但想法应该是清楚。在R中等价粘贴
的东西?非常感谢,
I know the syntax is wrong, but the idea should be clear. Something equivalent to paste
in R? Thanks much,
推荐答案
内置方法 globals()返回表示当前全局符号表的字典。
The builtin method globals() returns a dictionary representing the current global symbol table.
您可以添加变量到 globals
是这样的:
You can add a variable to globals
like this:
globals()["v" + str(i)] = i**2
FYI :这是回答你的问题,但肯定不是推荐的方式。直接操作 globals
是黑客解决方案,大多数情况下可以避免使用更清洁的替代方案。 (查看此主题中的其他评论)
FYI: This is the answer to your question but certainly not the recommended way to go. Directly manipulating globals
is hack-solution that can mostly be avoided be some cleaner alternative. (See other comments in this thread)
这篇关于在python循环中使用迭代器作为变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!