Using a loop to create multiple variables

前端 未结 3 976
死守一世寂寞
死守一世寂寞 2020-11-30 15:57

Let\'s say I need to make 5 variables. Since this may need to be adjusted in the future, I\'m using a loop.

i = 0
for j in range(5):
    i += 1
    w[i] = f         


        
3条回答
  •  一整个雨季
    2020-11-30 16:32

    You'd better just use a list. It's more readable and safer.
    However, you can create variables in the global namespace using globals() dictionary:

    i = 0
    for j in range(5):
        i += 1
        globals()["w" + str(i)] = function(i)
    

    Use it like this:

    print (w1)
    

    However, that's probably not a good idea. You can accidentally override something in the namespace, which will cause hard to debug bugs. Really, try not to do that.

    If you want to call them by name and not by index (as in a list), use your own dictionary:

    my_variables = {}
    i = 0
    for j in range(5):
        i += 1
        my_variables["w" + str(i)] = function(i)
    

    Then use like this:

    print (my_variables["w1"])
    

提交回复
热议问题