Use iterator as variable name in python loop

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

    # Python 3.8.2 (default, Feb 26 2020, 02:56:10)
    

    Creating variable names using globals() and unpacking a tuple using exec():

    glo = globals()
    listB=[]
    for i in range(1,11):
        glo["v%s" % i] = i * 10
        listB.append("v%s" % i)
    
    def print1to10():
        print("Printing v1 to v10:")
        for i in range(1,11):
            print("v%s = " % i, end="")
            print(glo["v%s" % i])
    
    print1to10()
    
    listA=[]
    for i in range(1,11):
        listA.append(i)
    
    listA=tuple(listA)
    print(listA, '"Tuple to unpack"')
    
    listB = str(str(listB).strip("[]").replace("'", "") + " = listA")
    
    print(listB)
    
    exec(listB)
    
    print1to10()
    

    Output:

    Printing v1 to v10:
    v1 = 10
    v2 = 20
    v3 = 30
    v4 = 40
    v5 = 50
    v6 = 60
    v7 = 70
    v8 = 80
    v9 = 90
    v10 = 100
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) "Tuple to unpack"
    v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 = listA
    Printing v1 to v10:
    v1 = 1
    v2 = 2
    v3 = 3
    v4 = 4
    v5 = 5
    v6 = 6
    v7 = 7
    v8 = 8
    v9 = 9
    v10 = 10
    

提交回复
热议问题