Python top 10 syntax

Keywords: Python Lambda less C

Preface

Python is a language that represents simple ideas. Its syntax is relatively simple and easy to use. However, it would be a mistake to overlook the subtlety and depth of Python syntax. This article carefully selected ten knowledge points that can best show the subtlety of Python syntax, and attached the detailed example code. If it can be integrated and used flexibly in the actual combat, it will make the code more refined and efficient, and at the same time, it will greatly improve the code B grid, making it look more sophisticated and read more elegant.

for - else

What? Isn't it if and else? No, you may not know that else is a two legged guy. For and else are also a couple, and they are legal. The top ten B grammar, for else, is definitely the nanwuwan! No, please see:

>>> for i in [1,2,3,4]:
print(i)
else:
print(i, 'I am else')

1
2
3
4
4 I am else

If there is a third if between for and else (within the loop), the relationship between for and else will not be affected. Because the level of for is higher than if, else is a guy who clings to the power. He doesn't care whether there is if or whether the statement that meets the if condition is executed. Else's eyes are only for. As long as the for is successfully implemented, else will run once

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

3
4
4 I am else

So, how to break up for and else? The else statement is skipped only when the for loop is interrupted by the break statement:

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

3

 

One star (*) and two stars (* *)

Have you found that the star (*) is really a magic symbol! Think about it. Without it, what's so interesting about C? Also, because of it, python will be so graceful, charming and charming! Python functions support default and variable parameters. One star represents an unlimited number of single valued parameters, and two stars represent an unlimited number of key value pair parameters.

Let's give an example: design a function to return the sum of multiple input values. Although we can make a list of these input values and pass them to the function, this method is far less elegant than using the variable parameters of a star:

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

>>> multi_sum(3,4,5)
12

Python functions allow all or part of the fixed parameters, default parameters, single value (one star) variable parameters, and key value pair (two stars) variable parameters to be used at the same time, which must be written in the above order.

>>> def do_something(name, age, gender='male', *args, **kwds):
print('Full 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: xuvive, 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 looks 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

 

3 yuan expression

Programmers familiar with C/C + + will miss classic ternary operators when they first start python, because it seems more troublesome to write in Python if they want to express the same idea. For example:

>>> y = 5
>>> if y < 0:
print('y It's a negative number')
else:
print('y It's a non negative number')

y It's a non negative number

In fact, python supports ternary expressions, but it's a little weird. For example: go to play ball, if it doesn't rain; if it rains, let's go to the study room. Translation into a ternary expression is:

Go play if it doesn't rain else go to the study room

Let's see the specific use of ternary expressions:

>>> y = 5
>>> print('y It's a negative number' if y < 0 else 'y It's a non negative number')
y It's a non negative number

python's ternary expression can also be used to assign values:

>>> y = 5
>>> x = -1 if y < 0 else 1
>>> x

 

with - as

The word with is not difficult to translate in English, but how to translate it in Python syntax, I can't think of it. It's basically a context management protocol. As a beginner, you don't need to pay attention to various methods and mechanisms of with, just need to understand its application scenarios. The with statement is suitable for some tasks that need to be prepared in advance and processed afterwards, such as file operation. You need to open the file first and close the file after the operation. If with is not used, the file operation is usually as follows:

fp = open(r"D:\CSDN\Column\temp\mpmap.py", 'r')
try:
contents = fp.readlines()
finally:
fp.close()

If with - as is used, it is much more elegant:

>>> with open(r"D:\CSDN\Column\temp\mpmap.py", 'r') as fp:
contents = fp.readlines()

 

List derivation

Among all kinds of bizarre syntax, list derivation should be used the most frequently, and the effect of code simplification is also obvious. For example, to find the square of each element in a list, you should usually write as follows (of course, there are other ways, 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]

If you use list derivation, it looks much more comfortable:

>>> a = [1, 2, 3, 4, 5]
>>> result = [i*i for i in a]
>>> result
[1, 4, 9, 16, 25]

 

Functions implemented in one line of Python code

In fact, derivations support not only lists, but also dictionaries, sets, tuples and other objects. If you are interested, you can do your own research. Next, I will briefly show the implementation of one line of code, which is all implemented by list derivation:

One line code print multiplication formula

print('\n'.join([' '.join(["%2s x%2s = %2s"%(j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]))

 

One line code printing maze

print(''.join(__import__('random').choice('\u2571\u2572') for i in range(50*24)))

 

A line of code starts your story

print('\n'.join([''.join([('Love'[(x-y) % len('Love')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0else' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))

                                    

One line code printing satellite turtle

print('\n'.join([''.join(['*' if abs((lambda a:lambda z,c,n:a(a,z,c,n))(lambda s,z,c,n:z if n==0 else s(s,z*z+c,c,n-1))(0,0.02*x+0.05j*y,40))<2 else ' ' for x in range(-80,20)]) for y in range(-20,20)]))

Various operations of list index

Python introduces negative integers as the index of arrays, which is absolutely a move of great popularity. Think about it. In C/C + +, if you want to get the last element of an array, you have to get the length of the array first, subtract one, and then index it, which seriously affects the consistency of thinking. The success of Python language, I personally think, among many factors, the convenience of list operation can not be ignored. Please see:

>>> 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 you are familiar with these things and often use them, then you will feel magical in the following usage:

>>> 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]

 

lambda function

lambda sounds very tall, but it's actually anonymous function (you must be familiar with anonymous function if you know js). What are the application scenarios of anonymous functions? It's only used where anonymous functions are defined, but not elsewhere, so you don't need to give it a cat and dog name. Here is an anonymous function for summation. There are two input parameters, X and Y. the function body is x+y. The return keyword is omitted.

>>> lambda x,y: x+y
<function <lambda> at 0x000001B2DE5BD598>
>>> (lambda x,y: x+y)(3,4) # Because anonymous functions have no name, they should be enclosed with parentheses

Anonymous functions are not used alone, but cooperate with other methods to provide built-in algorithm or judgment conditions for other methods. For example, when sorting multidimensional arrays or dictionaries with sorted, you can specify sorting rules.

>>> a = [{'name':'B', 'age':50}, {'name':'A', 'age':30}, {'name':'C', 'age':40}]
>>> sorted(a, key=lambda x:x['name']) # Sort by name
[{'name': 'A', 'age': 30}, {'name': 'B', 'age': 50}, {'name': 'C', 'age': 40}]
>>> sorted(a, key=lambda x:x['age']) # Sort by age
[{'name': 'A', 'age': 30}, {'name': 'C', 'age': 40}, {'name': 'B', 'age': 50}]

Let's take another example of square calculation of array elements. This time, use the map function:

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

1, 4, 9, 

 

yield and generators and iterators

  • The word yield is not easy to translate. It's useless to look up a dictionary. I'll just read it as "Yande". It's a foreign vocabulary. To understand yield, you need to understand the generator. To understand the generator, you need to know the iterator. Ha ha ha, are you dizzy? Come on, I'd better speak in vain.
  • In py2 era, range() returns list, but if range(10000000), it will consume a lot of memory resources. So, py2 has another xrange() to solve this problem. For py3, only xrange () is reserved, but range () is written. Xrange () returns an iterator that can be traversed like a list, but does not take up much memory. Generator is a kind of special iterator, which can only be traversed once. When the traversal is finished, it will disappear automatically. All in all, whether it's an iterator or a generator, it's to avoid using list and save memory. So, how do you get iterators and generators?

python has built-in iterator function iter, which is used to generate iterators. The usage is 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, 

yield is used to construct the generator. For example, we need to write a function that returns the square of all integers from 0 to a positive integer. The traditional code is as follows:

>>> 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]

But if you calculate the square of all integers within 100 million, the memory cost of this function will be very large. This is yield and you can show your skill:

>>> 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, 

If you iterate again, there will be no output.

Decorator

  • Just now I understand iterators and generators. Here's another decorator. Why are so many of them in Python? Indeed, python provides us with many weapons, and decorators are one of the most powerful. The decorator is very powerful. I'm trying to use a simple example to illustrate the usage and manufacturing process of the decorator from the perspective of demand.
  • If we need to define many functions, there are many solutions to show the running time of each function when it is running. For example, you can read the time stamp before calling each function, and then read the time stamp after the operation of each function, and then calculate the difference; you can also read the time stamp at the start and end positions in each function body, and finally calculate the difference. However, these two methods are not as simple and elegant as using decorators. The following example shows this well.
>>> import time
>>> def timer(func):
def wrapper(*args,**kwds):
t0 = time.time()
func(*args,**kwds)
t1 = time.time()
print('time consuming%0.3f'%(t1-t0,))
return wrapper

>>> @timer
def do_something(delay):
print('function do_something start')
time.sleep(delay)
print('function do_something End')


>>> do_something(3)
//Function do? Something
//End of function do? Something
//Time consuming 3.077

timer() is a decorator function defined by us. If you use @ to append it to any function (such as do ou something) definition, you will treat the newly defined function as the input parameter of the decorator function. Running the do UU something() function can be understood as executing timer (do UU something). Although the details are complex, the understanding will not deviate too much, and it is easier to grasp the manufacture and use of decorators.

 

Using assert skillfully

The so-called assertion means that the Boolean value of the declaration expression must be true, otherwise the assertion error exception will be triggered. Strictly speaking, assert is a debugging method, which should not be used in the production environment, but this does not affect our use of assertions to achieve some specific functions, such as input parameter format, type verification, etc.

>>> def i_want_to_sleep(delay):
assert(isinstance(delay, (int,float))), 'Function arguments must be integers or floating-point numbers'
print('Go to bed')
time.sleep(delay)
print('I wake up')


>>> i_want_to_sleep(1.1)
//Go to bed
//I wake up
>>> i_want_to_sleep(2)
//Go to bed
//I wake up
>>> i_want_to_sleep('2')
Traceback (most recent call last):
File "<pyshell#247>", line 1, in <module>
i_want_to_sleep('2')
File "<pyshell#244>", 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

Posted by John Rowe on Sun, 01 Mar 2020 19:31:00 -0800