"Reprint" Python dynamically generates variables

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.