In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how Python converts string constants into variables". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how Python converts string constants into variables".
1. How to generate variable names dynamically?
Student M's questions are as follows:
Excuse me, I'd like to ask you a question, how can I get a new list named after the elements in list A = [], B = [], C = [], D = [] when it is known as list = [A, B = [], C = [], D = []?
To put it simply, this problem means that the content of the string is used as the variable name of other objects.
The element in the list is a string, where the'A color color D'is a constant, and in the required result, A M D is a variable.
If you force a constant to be used directly as a variable, it will report an error:
>'A' = []... SyntaxError: can't assign to literal
Literal in error reporting refers to literal quantity, which is a common concept in computer science and is used to express fixed values in source code. For example, basic types such as integers, floating point numbers, strings, and so on, are literals.
Literal quantity refers to a quantity itself, which can be understood as an atomic entity and, of course, can no longer be assigned.
Therefore, the contents of the extracted string cannot be directly used as variable names, and we need to find another way.
Some beginners may wonder, is list [0] = [] all right? Of course not, because there is no A. What about A = list [0] and then A = []? That won't work either, because the A here is defined out of thin air, not generated from existing conditions.
At that time, only two or three students in the group participated in the discussion, and we didn't think of a solution. However, I think this topic is very interesting and worth pondering.
Because, if this problem can be solved, it means that variable names can be generated dynamically without pre-definition, which not only reduces the hassle of naming variables, but also enables automatic coding!
You can imagine the future, when artificial intelligence is writing code, if it can dynamically generate variable names according to known conditions, then the process of writing code will not be much easier? It is said that artificial intelligence is now ready to write code. I wonder what method it uses when taking the name of a variable. )
2. There is always a way
Recently, several advertisers have been mixed in the study group, so I decided to raise the threshold of examination, for example, to make an assessment with the questions in the group.
Unexpectedly, the first classmate Q, who was assessed, almost without thinking, came up with a way to solve the above problems. Coincidentally, almost at the same time, classmate J in the group gave another solution (he didn't see the discussion in the group, but saw the record of the planet of knowledge and knew about the problem).
In other words, the problem that I thought was unsolvable the night before was solved in two different ways the next day.
So what's their answer?
# J students' answers > list1 = ['A', 'Bao,' C','D'] > > for i in list1: > globals () [I] = [] > A []
This method cleverly "defines" new variables by modifying the global namespace. The globals () method takes out a dictionary, and the string'A' is one of the key values (key), which is exactly a variable in the global namespace, which translates from constants to variables.
At the data structure level, the empty list [] is bound to its string key value as a value, while at the application level, it is tied to the variable name as the content of the variable.
3. The method of dynamic code execution
Q, a new student in the group, provides a different answer:
Answer of # Q students > list1 = ['A', 'Bao,' C','D'] > > for i in list1: > exec (f "{I} = []") > A []
His writing uses the f-strings feature introduced by Python 3.6.In fact, it can also be implemented in a lower version by ensuring that the parameter received by the exec () method is a string containing the variable I, for example:
# the following code can replace line 4 exec (I + "= []") # or: exec ("{} = []" .format (I)) # or: exec (''.join ([I,' = []']))
The difference between these writing methods is only the difference in string concatenation. For more information about how to concatenate strings and the differences between different methods, see "Seven ways to concatenate strings in Python".
The core of Q's answer is the exec () method, which is built-in to execute code snippets stored in strings or files.
Its basic usage is as follows:
> exec ('x = 1 + 2') > x 3 # execution snippet > s = "> x = 10 > > y = 20 > > sum = x + y > print (sum) >"> exec (s) 30
After reading the usage of exec (), let's come back to see the answer of classmate Q. The I extracted from the for- loop is a string, and the concatenated string is processed by exec () to achieve the effect of dynamic coding.
That is, because the contents of the string constant are executed as valid code, the 'Amur color variable D' element takes a new identity and becomes the final Amurd variable name.
This method looks very simple, but because the exec () method is so obscure, we didn't wake up until classmate Q put forward it.
Note: in Python3, exec () is a built-in method; in Python2, exec is a statement (statement), and there is an execfile () method, which combines the two to become the exec () method in Python3. Python3 is used in this article.
At this point, I believe you have a deeper understanding of "how Python converts string constants into variables". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.