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
I know the syntax is wrong, but the idea should be clear. Something equivalent to paste in R? Thanks much,
解决方案
The builtin method globals() returns a dictionary representing the current global symbol table.
You can add a variable to globals like this:
globals()["v" + str(i)] = i**2
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)