How to string constants into variables?

1, how to dynamically generate variable names?
M students following question:

Excuse me everyone, ask questions, known list = [ 'A', 'B', 'C', 'D'], how can we get to the list of elements name of the new list A = [], B = [] , C = [], D = [] it?

Simple to understand, meaning the problem is that the string contents as variable names of other objects.

elements of the list is a string, where the 'A' - 'D' are constants, and the results are required, the AD is a variable.

If you force directly as a variable constant use, it will complain:

>>> 'A' = []
... SyntaxError: ASSIGN to literal CAN Not
given the literal it refers to a literal, which is a common computer science concept, for a fixed value expressed in the source code. Basic types such as integer, float, string, etc., is the literal.

Refers to a literal amount itself may be understood as an atomic entity, the course can not be assigned.

Therefore, the contents of the string out, and can not be directly used as a variable name, we need to think of other ways.

There are a beginner might think, list [0] = [] okay? Of course not, because there is no A appears. That A = list [0], then A = [] it? That's not OK, because A here is that you define out of thin air, rather than generated from existing conditions.

I think this topic is very interesting, it is worth pondering. Because, if we can solve this problem, it means that you can not make pre-defined, but dynamically generate variable names, which not only reduces the variable name to the trouble, but also to achieve the automatic coding!

Imagine the future of artificial intelligence at the time of writing the code, if based on known conditions, dynamically generate variable names, that process of writing code is not more smoothly it? (It is said that there are now artificial intelligence can write code, I wonder if it takes the variable name, what method is used?)

2, some way always
# J students answer
>>> List1 = [ 'A', 'B', 'C', 'D']
>>> I in List1 for:
>>> Globals () [I ] = []
>>> a
[]
this method to modify the global namespace, cleverly "define" a new variable. Globals () method is taken out of a dictionary, the string 'A' is wherein a key (Key), and this is precisely a key variable in the global namespace, which realize conversion from constant to variable.

On the structural level data, the empty list [] as a value (value) is saying the string key bound together, and in the application level, as bound with variable content and variable names.

See this answer, I suddenly remembered an article talking about is the problem of dynamically variable assignment ah! I seem to focus only on the globals () and locals () the difference between usage, but did not really grasp their original purpose.

J student said, he looked exactly the article, got scholarship this method. This is interesting, I shared a knowledge of their own gulping, then it is absorbed by J students to master, and finally fed back to solve my problem.

I really feel the charm of sharing knowledge: knowledge gained in the flow of life, shiny color in a collision.

At the same time, I also truly understand the benefits of a mutual learning groups: those who have altruistic self-interest, mutual aid were common progress.

3, dynamic method of executing code
Q provide students with a different answer:

# Q students to answer
>>> List1 = [ 'A', 'B', 'C', 'D']
>>> I in List1 for:
>>> Exec (F "{I} = []")
a >>>
[]
the way he uses the f-strings characteristic Python 3.6 was introduced, in fact, in the lower version, is achievable only need to keep exec () method comprising receiving a parameter variable i the string can be, for example, write:

The following code # alternative embodiment of the fourth row on
Exec (+ I "= []")
# or:
Exec ( "{} = []" the format (I).)
#, Or:
Exec ( '' .join ([ i, '= []'] ))
difference between these types of writing only difference string concatenation method on how string concatenation, and the difference between different methods, see "seven ways Python string concatenation."

Q students answer lies in the core exec () method, which is built-in, use is executing code segments stored in a string or file.

It is based on usage as follows:

>>> exec('x = 1 + 2')
>>> x
3

# Execute code segments
>>> S = "" "
>>> X = 10
>>> Y = 20 is
>>> SUM = X + Y
>>> Print (SUM)
>>>" ""
>>> Exec ( S)
30
read the exec () usage, we are back to see Q classmates answer. for- cycle i is taken out of the string, strings processed through the stitched exec (), the effect is obtained of the dynamic coding.

In other words, because the contents of the string constants are as effective implementation of the code, in which the 'A' - 'D' elements, you get a new identity, became final AD variable name.

This method looks very simple ah, but the exec () method too esoteric, until Q auditorium, we had an awakening.

Note: In the Python3, exec () is a built-in method; in the Python2, Exec is a statement (Statement), there is additionally the execfile () method, the two phases are combined, it would exec () method of Python3. As used herein, is Python3.

4, summary
abstract about the initial problem, it is actually asking is "How to string contents as variable names of other objects", further to say what is - "How to constant into a variable."

Use the static method directly assignment, it does not work.

The method proposed two students are dynamic indirect method: one is dynamically variable assignment, by modifying the namespace variable implanted; a dynamically execute code, can be said that through the "back door" approach, placement of variable .

Both methods the same thing, whether it is white or black, they are caught mice.

Both methods have brought us valuable inspiration, at the same time as they are, it is small partners to discuss a number of topics associated divergence within the group, such as: S students proposed an alternative modification namespace writing variables, L students referred to the eval () sense, the difference between eval () and exec (), I found the safe usage Why caution eval (), C and H students referred to the eval () is ......

Although certain topics can not be fully developed in a group chat, however, these links extend knowledge of the topic, greatly enriched the problem at the beginning of this article, which is a tiny problem, it involved two large body of knowledge.

Guess you like

Origin www.cnblogs.com/hyhy904/p/10954432.html