Use iterator as variable name in python loop

前端 未结 5 1820
有刺的猬
有刺的猬 2021-02-04 16:57

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,

5条回答
  •  长情又很酷
    2021-02-04 17:51

    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)

提交回复
热议问题