[Turn] on the Python syntax ten tall

Python is a language represents the simple idea that grammar is relatively simple, very easy to use. However, if this overlooked Python syntax subtle and profound, it would be wrong. This article carefully selected ten best show exquisite knowledge of the Python syntax, with a detailed code examples. As can mastery in combat, flexible use, will make the code more refined and efficient, but also greatly enhance code B cell to make it look more sophisticated, read more elegant.

1. for - else

what? Not if and else is the wife do? No, you may not know, else it both ways is a guy, for, and also a pair else, but is legal. Ten loaded B grammar, for-else absolutely no claim to the South Bay! I do not believe, see:

For I in >>> [1,2,3,4]:
Print (I)
the else:
Print (I, 'I'm the else')

. 1
2
. 3
. 4
. 4 I'm the else
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
if (loop body) if there is a third party get involved in between for and else, it will not affect relations for and else. Because for higher level than if, else is a guy elite cling, do not care whether there is if, and whether the conditions are satisfied if the statement. else only has eyes for, for as long as smoothly finished, else it will fart fart Britain child Britain children to run again:

>>> for i in [1,2,3,4]:
if i > 2:
print(i)
else:
print(i, '我是else')

3
4
4 And I was else
1
2
3
4
5
6
7
8
9
So how else break up and for this confrontation it? Only when the cycle is interrupted for break statement, will skip the else statement:

>>> for i in [1,2,3,4]:
if i>2:
print(i)
break
else:
print(i, '我是else')

. 3
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
2. a star (*) and two stars (**)

There are not found, the star (*) is a magical symbol! Think about it, without it, C language as well as what fun? Also, because of it, Python will be so graceful, graceful, lovely! Python function supports default parameters and variable parameters, a star that an unlimited number of single-value parameter, two stars represent an unlimited number of key parameters.

We illustrate it: design a function that returns multiple input values ​​and. Of course, we can make a list of these input values ​​passed to the function, but this method is far from a star using variable parameters is more elegant:

>>> def multi_sum(*args):
s = 0
for item in args:
s += item
return s

Multi_sum >>> (3,4, 5)
12 is
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
the Python function allows simultaneous use of all or part of the fixed parameter, default parameter, the value of single (one star) variable parameters, key-value pair (two Stars) variable parameters, the order must be written in accordance with the use.

>>> def do_something (name, age, gender = ' M', * args, ** kwds):
Print ( 'Name:% s, Age:% d, Gender:% s'% (name, age, gender) )
Print (args)
Print (kwds)

>>> do_something ( 'xufive', 50 , ' M', 175, 75, math = 99, english = 90)
Name: xufive, Age: 50, Gender: Male
(175, 75)
{ 'the Math': 99, 'Dictionary Dictionary English': 90}
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
Further, a star and the two stars may also be used for lists, tuples, unpacked dictionary, look more like C language:

>>> a = (1,2,3)
>>> print(a)
(1, 2, 3)
>>> print(*a)
1 2 3
>>> b = [1,2,3]
>>> print(b)
[1, 2, 3]
>>> print(*b)
1 2 3
>>> 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
3. 三元表达式

Familiar with C / C ++ programmers to get started early when python, will miss the classic ternary operator, because I wanted to express the same idea, using python seem to be more trouble to write. such as:

Y =. 5 >>>
>>> IF Y <0:
Print ( 'Y is a negative')
the else:
Print ( 'Y is a non-negative')

y is a non-negative
1
2
3
4
5
6
7
In fact, python is a triplet of expressions of support, just a little bit weird, like we Shandong people speak. For example, most people like to use flip Shandong sentence: Go play, and if it does not rain; rain, let's go to study hall. Is translated into a triplet of expressions:

Go play if it does not rain else to go to study room
to look at the specific use of a triplet of expressions:

Y =. 5 >>>
>>> Print ( 'Y is a negative' if y <0 else 'y is a non-negative')
Y is a non-negative number
. 1
2
. 3
ternary expressions with python assignment can also be used:

>>> y = 5
>>> x = -1 if y < 0 else 1
>>> x
1
1
2
3
4
4. with - as

with that word, the English translation of which is not difficult, but how to translate the Python syntax, I really can not think, generally is a context management protocol. As a beginner, various methods and mechanisms of no concern with how, just know its scenarios on it. with statements need to be prepared in advance for some of the tasks to be processed after the event, for example, file operations, you need to open the file, after the completion of the operation need to close the file. If you do not use with, file operations usually get this:

Open = FP (R & lt "D: \ CSDN \ the Column \ TEMP \ mpmap.py", 'R & lt')
the try:
Contents = fp.readlines ()
the finally:
fp.close ()
. 1
2
. 3
. 4
. 5
if used with - as , it is more elegant:

Open with >>> (R & lt "D: \ CSDN \ the Column \ TEMP \ mpmap.py", 'R & lt') AS FP:
Contents fp.readlines = ()
. 1
2
5. The list of derivation formula

In various strange syntax list derived using the formula of the highest frequency to be, for the effect of the code is also very simplified significantly. For example, find a list of the elements of the square, usually should be written (of course there are other formulations, such as using the map function):

>>> a = [1, 2, 3, 4, 5]
>>> result = list()
>>> for i in a:
result.append(i*i)

Result >>>
[. 1,. 4,. 9, 16, 25]
. 1
2
. 3
. 4
. 5
. 6
. 7
If the list comprehension, looks more comfortable:

A = >>> [. 1, 2,. 3,. 4,. 5]
>>> Result = [I I * for I in A]
>>> Result
[. 1,. 4,. 9, 16, 25]
. 1
2
. 3
. 4
fact on the derivation not only support list, also supports dictionaries, sets, tuples and other objects. Are interested, they can study on their own. I have a blog post "What is the function of frenzied line of Python code to achieve? "Examples of which are the list comprehensions achieved.

6. The list of indexes show various operations

Python introduce negative integers as the array index, which is definitely a big hi Ben & Poor's move. Think about it, in C / C ++, you want the last element of the array, it must first obtain the array length, indexed after a cut, seriously affect the continuity of thought. The reason why the success of the Python language, I think, in which many factors, convenience, a list of actions that can not be ignored. Take a look:

>>> 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[1::2]
[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 we say that you are familiar with these, too often, then the next this usage, you will feel amazing:21201918171615141312111098765432
1




















>>> a = [0, 1, 2, 3, 4, 5]
>>> b = ['a', 'b']
>>> a[2:2] = b
>>> a
[0, 1, 'a', 'b', 2, 3, 4, 5]
>>> a[3:6] = b
>>> a
[0, 1, 'a', 'a', 'b', 4, 5]
1
2
3
4
5
6
7
8
7. lambda函数

It sounds great on high lambda, in fact, an anonymous function (js students understand must be very familiar with the anonymous function). What scenarios anonymous function is it? This function is used only in the anonymous function definitions place less than other places, so we do not need to give it a Amaoagou like the name. The following is a summation of anonymous function has two input parameters, x and y, the function body is x + y, is omitted return keyword.

The lambda the X->>>, the y-: the y-the X-+
<function <the lambda> AT 0x000001B2DE5BD598>
>>> (the X-the lambda, the y-: the X-+ the y-) (3, 4) # no name because the anonymous function, use the time to use parentheses wrap it
. 1
2
. 3
anonymous function is generally not used alone, but in conjunction with other methods, or algorithms providing built determination condition other methods. For example, when using the sort function sorted to sort multidimensional array or dictionary, you can specify a collation.

>>> a = [{ 'name' : 'B', 'age': 50}, { 'name': 'A', 'age': 30}, { 'name': 'C', 'age' : 40}]
>>> the sorted (A, X the lambda = Key: X [ 'name']) # sorted by name
[{ 'name': 'A ', 'age': 30}, { 'name': ' B ',' Age ': 50}, {' name ':' C ',' Age ': 40}]
>>> the sorted (A, X the lambda = Key: X [' Age ']) # by age
[ { 'name': 'A', 'Age': 30}, { 'name': 'C', 'Age': 40}, { 'name': 'B', 'Age': 50}]
. 1
2
. 3
. 4
. 5
another example of the array element squared, with the map function:

>>> a = [1,2,3]
>>> for item in map(lambda x:x*x, a):
print(item, end=', ')

. 1,. 4,. 9,
. 1
2
. 3
. 4
. 5
8. The generator as well as the yield and iterator

yield this word, really bad translation, translation dictionary is useless. I just attended as "a love", be it foreign words. To understand yield, we must first understand the generator (generator). To understand the generator, get to know iterator (iterator). Ha ha ha, the halo around it? Well, I still say it vernacular.

Saying py2 era, range () returns a list, but if the range (10000000), it will consume a lot of memory resources, so, py2 has carried out a xrange () to solve this problem. py3 only retained xrange (), but writing range (). xrange () returns an iterator is, as it can be traversed like a list, but do not take up much memory. generator (generator) is a special iterator, can only be traversed once, traversing the end, it automatically disappears. In short, whether it is an iterator or generator, it is to avoid using the list, thus saving memory. So, how to get iterators and generators do?

ITER python built iterative function, for generating the iterator is used as follows:

>>> a = [1,2,3]
>>> a_iter = iter(a)
>>> a_iter
<list_iterator object at 0x000001B2DE434BA8>
>>> for i in a_iter:
print(i, end=', ')

. 1, 2,. 3,
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
the yield is used to construct the generator. For example, we write a function that returns a positive integer from 0 to a square of all integers, is the traditional writing this code:

>>> def get_square(n):
result = list()
for i in range(n):
result.append(pow(i,2))
return result

Print >>> (get_square (. 5))
[0,. 1,. 4,. 9, 16]
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
, but calculating the square of all integers, if less than 1 million, the memory overhead function will be very large, this is the yield you can flourish:

>>> def get_square(n):
for i in range(n):
yield(pow(i,2))

>>> a = get_square(5)
>>> a
<generator object get_square at 0x000001B2DE5CACF0>
>>> for i in a:
print(i, end=', ')

0, 1, 4, 9, 16,
1
2
. 3
4
. 5
. 6
. 7
. 8
9
10
. 11
if traversed again, there will be no output.

9. decorator

Just figure out iterators and generators, which came a decorator, Python why so much is it? Indeed, Python provides a lot of weapons, decorator is one of the most powerful weapon for us. Decorator is very strong, I am here to try from the perspective of demand, with a simple example of how the decorator methods and manufacturing processes.

If we need to define a number of functions, each function when running this function to display the long run, there are many solutions. For example, you can read about each function before calling time stamp, after the end of each run function to read the time stamp, difference can; you can read the time stamp at the beginning and end of each function in the body, the final demand difference. However, these methods are not used decorator so simple and elegant. The following example illustrates this well.

>>> import time
>>> def timer(func):
def wrapper(*args,**kwds):
t0 = time.time()
func(*args,**kwds)
t1 = time.time()
print('耗时%0.3f'%(t1-t0,))
return wrapper

@Timer >>>
DEF do_something (Delay):
Print ( 'function do_something start')
the time.sleep (Delay)
Print ( 'end function do_something')


>>> do_something (3)
function do_something start
function do_something end
Processed 3.077
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
13 is
14
15
16
. 17
18 is
. 19
20 is
Timer () is a function of decorator We define, using the @ it before any additional function (such as do_something) is defined, equal to the newly defined function, the input parameters as a function of the decorator. Run do_something () function, it can be understood as the implementation of a timer (do_something). Although the details of the complex, but not too much deviation so understandable and easier to grasp the manufacture and use decorators.

10. Using assertions assert

The so-called assertions, the statement is a Boolean value expression must be true for judgment, otherwise it will trigger the AssertionError. Strictly speaking, assert debugging tools, it should not be used in a production environment, but this does not affect our use assertions to achieve some specific functions, such as the format of the input parameters, the type of verification.

DEF i_want_to_sleep >>> (Delay):
Assert (the isinstance (Delay, (int, a float))), 'must be a function parameter integer or floating'
Print ( 'sleeping start')
the time.sleep (Delay)
Print ( 'sleeping Woke up')


>>> i_want_to_sleep (1.1)
began to sleep
woke up
>>> i_want_to_sleep (2)
began to sleep
woke up
>>> i_want_to_sleep ( '2')
Traceback (MOST recent Results Last Call):
File "<pyshell # 247>", . 1 Line, in <Module1>
i_want_to_sleep ( '2')
File "<244 pyshell #>", Line 2, in i_want_to_sleep
Assert (the isinstance (Delay, (int, a float))), 'must be a function parameter integer or floating '
AssertionError with: function parameter must be an integer or floating point
-------- switched csdn Tianyuan Joe ---

Guess you like

Origin www.cnblogs.com/nihao2020/p/12000241.html