Use iterator as variable name in python loop

前端 未结 5 1799
有刺的猬
有刺的猬 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:38

    While this does not attempt to answer the question directly (see geccos answer for that), this is generally the "approved" method for such an operation:

    v = [i**2 for i in range(3)]
    
    print v[0] # 0
    print v[1] # 1
    print v[2] # 4
    

    In general it is both cleaner and more extensible to use an ADT (a list in this case) to represent the given problem than trying to create "dynamic variables" or "variable variables".

    Happy coding.


    While the above uses indices, the more general form of "variable variables" is generally done with a dictionary:

    names = dict(("v" + str(i), i**2) for i in range(3))
    print names["v2"] # 4
    

    And, for a fixed finite (and relatively small) set of variables, "unpacking" can also be used:

    v0, v1, v2 = [i**2 for i in range(3)]
    print v1 # 1
    

提交回复
热议问题