Using a loop in Python to name variables

后端 未结 5 1411
说谎
说谎 2020-12-03 03:45

How do I use a loop to name variables? For example, if I wanted to have a variable double_1 = 2, double_2 = 4 all the way to double

5条回答
  •  余生分开走
    2020-12-03 04:11

    Although I doubt you really need to do what you want, here's a way:

    namespace = globals()
    for x in range(1, 13):
        namespace['double_%d' % x] = x * 2
    
    print double_1
    print double_2
       ...
    print double_12
    

    globals() returns a dictionary representing the current global symbol table (the dictionary of the current module). As you can see, it's possible to add arbitrary entries to it.

提交回复
热议问题