In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains the "Python grammar writing skills", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "what are the Python grammar writing skills" bar!
1. For-else
What? Aren't if and else the original match? No, you may not know, else is a guy on two boats, for and else are also a couple, and it's legal. Top ten B grammar, for-else can definitely be regarded as Nanwuwan! If you don't believe me, please take a look:
> for i in: print (I) else:print (I,'I'm else') 12344 I'm else
If there is a third party if insertion between for and else (in circulation), it will not affect the relationship between for and else. Because for is at a higher level than if, and else is a powerful guy, he doesn't care if there is an if and whether he executes statements that meet the if condition. Else only sees for, and as long as for is successfully implemented, else will run again and again:
> for i in: if I > 2:print (I) else:print (I,'I am else') 344 I am else
So, how to break up the enemies of for and else? The else statement is skipped only when the for loop is interrupted by the break statement:
> for i in: if I > 2:print (I) breakelse:print (I,'I am else') 3
two。 One star (*) and two stars (*)
Have you found that the star (*) is really a magical symbol! Think about it, without it, what is the fun of C language? Similarly, because of it, Python will be so elegant, graceful and charming! The Python function supports default and variable parameters, with one star representing an unlimited number of single-valued parameters and two stars representing an unlimited number of key-value pairs.
Let's give an example: design a function that returns the sum of multiple input values. We can list these input values to the function, but this method is far less elegant than using the variable parameters of a star:
> def multi_sum (* args): s = 0for item in args:s + = itemreturn s > multi_sum
The Python function allows all or part of the use of fixed parameters, default parameters, single-valued (one star) variable parameters, and key-value pairs (two stars) variable parameters, which must be written in the above order.
> def do_something (name, age, gender=' male', * args, * * kwds): print ('name:% s, age:% d, gender:% s% (name, age, gender) print (args) print (kwds) > do_something (' xufive', 50, male', 175,75, math=99, english=90) name: xufive, age: 50, gender: male (175,75) {'math': 99,' english': 90}
In addition, one star and two stars can also be used to unpack lists, tuples, and dictionaries, which look more like C language:
> a = (1 name':'xufive', 'age':51 3) > print (a) (1 pyrrine 2 age':51 3) > print (* a) 1 23 > b = [1 name 3] > print (b) [1 reprit 2] > print (* b) 1 23 > c = {' name':'xufive', 'age':51} > print (c) {' name':'xufive', 'age':51} > > print (* c) name age > print (' name: {name}, age: {age}'. Format (* * c)) name:xufive Age:51
3. Ternary expression
Programmers familiar with python + will miss the classic ternary operator when they start using python, because it seems more troublesome to write it in python to express the same idea. For example:
> y = 5 > if y
< 0:print('y是一个负数')else:print('y是一个非负数')y是一个非负数 其实,python 是支持三元表达式的,只是稍微怪异了一点,类似于我们山东人讲话。比如,山东人最喜欢用倒装句:打球去吧,要是不下雨的话;下雨,咱就去自习室。翻译成三元表达式就是: 打球去吧 if 不下雨 else 去自习室 来看看三元表达式具体的使用: >> > y = 5 > > print ('y is a negative number'if y
< 0 else 'y是一个非负数')y是一个非负数 python 的三元表达式也可以用来赋值: >> > y = 5 > x =-1 if y
< 0 else 1>> x1
4. With-as
The word with is not difficult to translate in English, but I can't figure out how to translate it in Python grammar. It's basically a context management protocol. As a beginner, you don't need to pay attention to the various methods and mechanisms of with, you just need to understand its application scenario. The with statement is suitable for some tasks that need to be prepared in advance and need to be handled afterwards, such as file operations, which need to open the file first and close the file after the operation is completed. If you do not use with, the file operation usually looks like this:
Fp = open (r "D:\ jb51\ Column\ temp\ mpmap.py",'r') try: contents = fp.readlines () finally: fp.close ()
If you use with-as, it's much more elegant:
> with open (r "D:\ jb51\ Column\ temp\ mpmap.py",'r') as fp:contents = fp.readlines ()
5. List derivation
Of all the bizarre grammars, list deductions should be used the most frequently, and the simplification of the code is also obvious. For example, to find the square of each element of a list, you should usually write like this (of course, there are other ways to write it, such as using the map function):
> a = [1,2,3,4,5] > > result = list () > for i in a:result.append (iTuni) > result [1,4,9,16,25]
If you use list derivation, it looks much more comfortable:
> a = [1, 2, 3, 4, 5] > result = [iTuni for i in a] > result [1, 4, 9, 16, 25]
In fact, deduction supports not only lists, but also dictionaries, collections, tuples, and so on. If you are interested, you can study it yourself. I have a blog post, "what crazy functions can a single line of Python code achieve?" The examples in it are all list-driven.
6. 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]
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 = ['ajar,' b'] > > a [2:2] = b > > a [0,1, 'averse,' baked, 2,3,4,5] > > a [3:6] = b > > a [0,1, 'ajar,' aura, 'baked, 4,5]
7. 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 xpeny: XQuery > > (lambda xpeny: Xpeny) (3pr 4) # because the anonymous function does not have a name, you should wrap it in parentheses when using 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}]
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
8. 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=',')
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]
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
If you traverse again, there will be no output.
9. 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.077
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.
10. 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
Thank you for your reading, these are the contents of "what are the skills for writing Python grammar?" after the study of this article, I believe you have a deeper understanding of the skills of writing Python grammar, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.