In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "Python grammar example analysis". In daily operation, I believe many people have doubts about Python grammar example analysis. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "Python grammar example analysis". Next, please follow the editor to study!
1. Various coquettish operations of list index
Python is absolutely delighted to introduce negative integers as the index of the array. Come to think of it, if you want the last element of an array, you have to get the length of the array first, and then index it after minus one, which seriously affects the coherence of thinking. The reason for the success of the Python language, I personally think, among many factors, the convenience of list operation can not be ignored. Please look at:
> > a = [0,1,2,3,4,5] > > a [2:4] [2,3] > > a [3:] [3,4,5] > > a [1:] [1,2,3,4,5] > > a [:] [0,1,2,3,4,5] > > a [: 2] [0,2,4] > > a [1veve2] [1,3,5] > > a [- 1] 5 > > a [- 2] 4 > a [1: 1] [1,2,3] 4] > a [::-1] [5, 4, 3, 2, 1, 0] 123456789101112131415161718192021
If you are familiar with all these and use them often, you will feel magical about the following usage:
> a = [0,1,2,3,4,5] > > b = ['asides,' b'] > > a [2:2] = b > > a [0,1, 'averse,' baked, 2,3,4,5] > > a [3:6] = b > > a [0,1, 'asides,' asides, 'baked, 4,5] 12345678
2. Lambda function
Lambda sounds high-end, but it is actually anonymous functions (students who know js must be familiar with anonymous functions). What is the application scenario of anonymous functions? Use this function only where you define an anonymous function, not anywhere else, so you don't need to give it a name like a cat or a dog. Here is an anonymous summation function with two input parameters, x and y, and the function body is x _ sum _ y, omitting the return keyword.
> lambda XQuery y: XQuery > > (lambda XQuery y: XQuery) (3pr 4) # because anonymous functions do not have a name, wrap it in parentheses when you use it
Anonymous functions are generally not used alone, but in conjunction with other methods to provide built-in algorithms or judgment conditions for other methods. For example, you can specify a collation when you use the sorting function sorted to sort multidimensional arrays or dictionaries.
> a = [{'name':'B',' age':50}, {'name':'A',' age':30}, {'name':'C',' age':40}] > sorted (a, key=lambda XRX ['name']) # sort by name [{' name':'A', 'age':30}, {' name':'B', 'age':50}, {' name':'C'] 'age': 40}] > sorted (a, key=lambda XRX [' age']) # sorted by age [{'name':' A', 'age': 30}, {' name':'C', 'age': 40}, {' name': 'Bund,' age': 50}] 12345
Take another example of squaring array elements, this time using the map function:
For item in map (lambda x:x*x, a): print (item, end=',') 1,4,9, 12345
3. Yield and generators and iterators
The word yield is really hard to translate, and it's no use turning to a dictionary. I'll just read it as "one love", which can be regarded as a foreign word. To understand yield, you need to know generator (generator). To understand generator, you need to know iterator (iterator). Ha, are you dizzy? Forget it. I'll speak vernacular.
In the py2 era, range () returned list, but if range (10000000), it would consume a lot of memory resources, so py2 created another xrange () to solve this problem. Py3 retains only xrange (), but writes range (). What xrange () returns is an iterator that can be traversed like list without consuming much memory. Generator (generator) is a special iterator that can only be traversed once, and then disappears automatically when the traversal is over. In short, both iterators and generators are designed to avoid using list, thereby saving memory. So, how do you get iterators and generators?
Python has a built-in iterative function iter, which is used to generate iterators as follows:
> a = [1BI end=', 3] > a_iter = iter (a) > > a_iter > for i in a_iter:print (I, end=',') 1Jing 2Jing 3, 12345678
Yield is used to construct generators. For example, we want to write a function that returns the square of all integers from 0 to a positive integer. The traditional code goes like this:
> def get_square (n): result = list () for i in range (n): result.append (pow (iMagne2)) return result > print (get_square (5)) [0,1,4,9,16] 12345678
But if you calculate the square of all integers less than 100 million, the memory cost of this function will be very large, which is what yield can do:
> > def get_square (n): for i in range (n): yield (pow (iMagne2)) > a = get_square (5) > > a > for i in a:print (I, end=',') 0,1,4,9,16,1234567891011
If you traverse again, there will be no output.
4. Decorator
Just figured out iterators and generators, this is another decorator, Python why so many? Indeed, Python provides us with a lot of weapons, and the decorator is one of the most powerful weapons. The decorator is very powerful, and I will try to use a simple example to illustrate the use and manufacturing process of the decorator from the point of view of requirements.
If we need to define many functions, there are many solutions to show the running time of each function while it is running. For example, you can read the timestamp before calling each function, and then read the timestamp after the end of each function, or you can read the timestamp on the start and end position of each function, and finally find the difference. However, neither of these methods is as simple and elegant as using a decorator. The following example shows this very well.
> > import time > def timer (func): def wrapper (* args,**kwds): T0 = time.time () func (* args,**kwds) T1 = time.time () print ('time consuming% 0.3% (t1-t0,)) return wrapper > > @ timerdef do_something (delay): print (' function do_something start') time.sleep (delay) print ('function do_something end') > > do_something (3) function do_something start function do_something end time 3.07712345678910111213141516181920
Timer () is our defined decorator function, and using @ to append it to any function definition (such as do_something) is tantamount to taking the newly defined function as the input parameter of the decorator function. Running the do_something () function can be understood as executing timer (do_something). Although the details are complex, this understanding will not deviate too much, and it is easier to grasp the manufacture and use of the decorator.
5. Skillful use of assertion assert
The so-called assertion is to declare that the Boolean value of the expression must be true, otherwise an AssertionError exception will be triggered. Strictly speaking, assert is a means of debugging and should not be used in a production environment, but this does not affect us to use assertions to achieve some specific functions, such as the format of input parameters, type verification, and so on.
> def i_want_to_sleep (delay): assert (isinstance (delay, (int,float)), 'function argument must be integer or floating point' print ('start sleeping') time.sleep (delay) print ('wake up') > > i_want_to_sleep (1. 1) start to sleep and wake up > > i_want_to_sleep (2) start sleeping and wake up > > i_want_to_sleep ('2') Traceback (most recent call last): File " Line 1, in i_want_to_sleep ('2') File "", line 2, in i_want_to_sleep assert (isinstance (delay, (int,float), 'function arguments must be integers or floating point numbers' AssertionError: function arguments must be integers or floating point numbers to this point The study of "Python Grammar example Analysis" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.