Use iterator as variable name in python loop

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

    There are a few ways to do this, the best will depend on what you actually want to do with the variables after you've created them.

    globals() and locals() will work but they're not what you want. exec() will also work but it's even worse than globals() and locals().

    A list comprehension as mentioned by @user166390 is a good idea if v1, v2 and v3 are homogenous and you just want to access them by index.

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

    You could also do this, if it's always exactly three elements:

    >>> v1, v2, v3 = [i ** 2 for i in range(3)]
    >>> v1
    0
    >>> v2
    1
    >>> v3
    2
    

    This is nice if the objects are more individual because you can give them their own names.

    Another in-between option is to use a dict:

    d = {}
    for i, val in enumerate(range(3)):
        d["v{}".format(i)] = val
    
    >>> d["v0"]
    0
    >>> d["v1"]
    1
    >>> d["v2"]
    4
    

    Or a shortcut for the above using a dict comprehension:

    d = {"v{}".format(i): val for i, val in enumerate(range(3))}
    

提交回复
热议问题