Create multiple variables with a Python loop, such as creating a1=, a2=, a3=, a4=, a5=
Can be done with Python's built-in function locals
Locals is a built-in function of Python, and he can access local and global variables in a dictionary way.
Python uses namespaces to record variables, like JavaScript's window, which records various global variables.
Each module, each function has its own namespace, which records the names and values of variables, constants, and classes.
Just like JS, when Python uses variables, it follows these steps to search:
1. Local variables of a function or class.
2, global variables.
3, built-in variables.
The above three steps, one of the steps to find the corresponding variable, will not look down. If none of the three steps are found, an exception is thrown.
Python can also dynamically generate variables like JavaScript. We look at the dynamically generated variables of javascript:
1 var obj = {}; 2 for (var i =0, len = ten; i < Len; i++) {3 obj[' a ' + i] = i; 4 }56//{' a0 ': 0, ' A1 ': 1 ....., ' A9 ': 9}
The locals method in Python
1 createvar = locals () 2 listtemp = range (1,10 3 for i,s enumerate (listtemp): 4 createvar[ a " +i] = s print a1,a2,a3 6 # ...
1 def Foo (args): 2 x=1 Print locals () 4 5 foo (123 6 7 # will get {' arg ': 123, ' X ': 1}
1 for in range (3):2 locals () ['a'+str (i)]=i3 print'a'+str (i)
Print Result: Variable name: a0 A1 A2 corresponding value a0=0 a1=1 a2=2
Tip: Creating a dictionary dynamically brings additional overhead, and if you can, specify key-value pairs as much as possible.
Reprinted from: http://www.cnblogs.com/zzbo/p/3391453.html
"Reprint" Python dynamically generates variables