[python Programming] - Summary of knowledge points in the introductory series

Posted by westmich on Fri, 17 Sep 2021 13:38:41 +0200

The first three articles of this blog: a detailed summary and introduction of the knowledge points of introductory Series 1, 2 and 3.

1. Method of creating two-dimensional matrix

There are mainly the following:

l1=[[0 for i in range(3)] for j in range(3)]
for i in range(3):
    for j in range(3):

l2=[[] for i in range(3)]
for i in range(3):
    for j in range(3):

for i in range(3):
    for j in range(3):

The first one above is to directly create a two-dimensional array with all zeros and assign initial values, so it can be referenced directly with subscripts; The second and third methods generate two-dimensional arrays through insertion, as shown in the figure, using the append method. The first is recommended.

2. Conversion between list (tuple) and dictionary

(1) Conversion between string and list (tuple)

String - > list or tuple: each character in the string is an element in the list (tuple)

List (tuple) - > string: convert the whole list or tuple into a string, including quotation marks of the elements inside, commas between tuples, and [] and () signs.

(2) Dictionary to list (tuple)

Direct conversion only converts keys to the past by default. You can also convert keys and values respectively:


[1, 2]
[1, 2]
['a', 'b']

How to access the dictionary:


for key,value in dic.items():# Directly access the key and the corresponding value, using the dic.items() method
for key in dic.keys(): #To access all the keys, use the dic.keys() method
for value in dic.values():

(3) Convert list (tuple) to dictionary

First, lists cannot be converted directly to dictionaries.

The first method uses the zip() function to combine the elements in two lists (tuples) to form keys and corresponding values. At the same time, note that when the two lists are different in length, the extra elements have no matching elements in the other list, and the dictionary does not display the extra elements.

a = ['a1','a2','a3']
b = ['b1','b2']
d = zip(a,b)

{'a1': 'b1', 'a2': 'b2'}

The second method uses nested lists. This requires that there can only be two elements in the two lists. The elements in the list are combined by themselves, and the elements of each list are paired with keys and values.

a = ['a1','a2']
b = ['b1','b2']
c = [a,b]

{'a1': 'a2', 'b1': 'b2'}

# It is equivalent to traversing the sub list, as follows
# dit = {}
# for i in c:
#     dit[i[0]] = i[1]

3. Reverse output list

There are two methods, one is to reverse the output (and provide a method to traverse the list: the three colon method), and the other is to use the list.reverse() method. Note that the latter has no return value and directly reverses the original list:


for i in l1[::-1]:

[4, 3, 2, 1]

Traversal list: [:]. Parameter 1 is 0 by default, parameter 2 is the last element by default, and parameter 3 represents interval, which is 1 by default. Generally, parameter 2 is not written when accessing the last element.

4. lambda creates anonymous functions

python uses lambda to create anonymous functions. Lambda is just an expression, and the function body is much simpler than def.

——The theme of lambda is an expression, not a block of code. Only limited logic can be encapsulated;

——lambda function has its own namespace and cannot access parameters other than its own parameter list or global parameters;

The syntax of the lambda function contains only one statement:

fun_name = lambda arg1,arg2 : expression

Where arg2 and arg2 are parameters, and there can be several. The expression is after the colon, and the function name is at the front.

Examples are as follows:

sum = lambda x,y : x+y

Example 2: compare larger or smaller values

MAXIMUM = lambda x,y :  (x > y) * x + (x < y) * y
MINIMUM = lambda x,y :  (x > y) * y + (x < y) * x
if __name__ == '__main__':
    a = 10
    b = 20
    print ('The largar one is %d' % MAXIMUM(a,b))
    print ('The lower one is %d' % MINIMUM(a,b))

Summary: lambda is a way to create simple functions. The function body can only achieve a single function, that is, a line of expression, which is generally useless.

5. View methods of built-in functions

View documents by__ doc__, Take abs as an example__ doc__.


def square(num):
    '''Return the square value of the input number.
    The input number must be integer.
    return num ** 2


Return the square value of the input number.
    The input number must be integer.

6. python generates random numbers

Random number generation in python mainly uses random module and random function in numpy library.

The former is mainly used to generate random numbers and select random numbers and random number sequences in the sequence, and the latter is used to generate a*b-dimensional random matrix.

Here is a brief description of the following, see the blog for details: http://(58 messages) [python Programming] - python generates random numbers_ Yang's blog - CSDN blog

(the link seems useless, I don't know why) that is another blog in this series: python generates random numbers.

(1) random.random(): randomly generate a floating-point number of [0, 1)

(2) random.uniform(a, b): randomly generate a floating-point number of [a, b)

(3) Random. Random (a, b): randomly generate an integer of [a, b)

(4) Random. Random (a, B, step): randomly select a number in a randomly generated integer sequence starting with < A, increasing every step, and ending with b >

(5) random.choice(sequence): randomly select an element from an existing sequence

(6) random.sample(sequence,k): obtain fragments of a specified length from a sequence (k are randomly selected, without sequence)

(7) Random. Shuffle (list): disrupt the element order of a list (the list itself is disrupted, and there is no return value)

(8) np.random.randn(a, b): generate a*b-dimensional random number, and the number follows the standard positive Taiyuan distribution (there can be several parameters)

(9) Random. Random (low, high, size): generate a random integer matrix with < low as the lower limit, high as the upper limit and size >, in which the numerical range includes low and does not include high

7. Output method: sys.stdout.write() method

By default, the print method prints line breaks after output, while the stdout.write() method outputs without line breaks, which is equivalent to the printf function in C + +.

from sys import stdout
for i in range(10):
    for j in range(i + 1):
        stdout.write(' ')

1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 
1 6 15 20 15 6 1 
1 7 21 35 35 21 7 1 
1 8 28 56 70 56 28 8 1 
1 9 36 84 126 126 84 36 9 1 

8. Some use of time library

(1) Pause output function sleep()

time.sleep(sec) method to make the screen output sec seconds late.

(2) Format output time.strftime()

Use the localtime in the time library to know the current time, and then use time. Strftime (format, t). Format is the format, and the parameter t is a structured time string.

import time
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

time.struct_time(tm_year=2021, tm_mon=9, tm_mday=15, tm_hour=19, tm_min=33, tm_sec=6, tm_wday=2, tm_yday=258, tm_isdst=0)
2021-09-15 19:33:06

9. Define class in Python

Classes in python mainly include the following parts: class variables, instance variables, construction methods _init _, (instance) methods.

Class variables belong to the class itself and are used to define the state data contained in the class itself, while instance variables belong to the object of the class and are used to define the data contained in the object; methods are used to define the behavior or function implementation of the object of the class.

The method defined in the class is the instance method by default. The method defining the instance method is basically the same as the method defining the function, except that the first parameter of the instance method will be bound to the caller of the method (the instance of the class). Therefore, the instance method should define at least one parameter, which is usually named self.

There is a special method in the instance method: _init_, which is called the constructor. The constructor is used to construct the object of this class. Python returns the object of this class by calling the constructor (new is not required).

class Person :
    'This is a study Python A defined Person class'
    # A class variable is defined below
    hair = 'black'
    def __init__(self, name = 'Charlie', age=8):
        # Next, add two instance variables for the Person object
        self.name = name
        self.age = age
    # A say method is defined below
    def say(self, content):




(1) Note that the following two types of variables can be distinguished. Class variables belong to class and instance variables belong to object. When defining objects belonging to this class, use the construction method _init _ _, and pass in the instance variable parameters to construct the object;

(2) When defining all methods, at least one incoming parameter, self, is bound to the caller of the method;

(3) When defining a class object, if the parameter is passed in, the value will be assigned according to the passed in parameter, and if there is no parameter, the default value will be taken. So for constructors in classes__ init__ Generally, default values are assigned to variables.

10. About function if__ name__== '__ main__'

(1) Execution process and results

A python file usually has two execution methods: one is to run it directly as a script, and the other is to import it into other Python scripts to be called (module reuse) for execution. therefore   if __name__ == '__main__' This is the code execution process that controls these two situations.

Here's the point: in   if __name__ == '__main__' The code under the control of is executed only when the first case (i.e. as a script) is run, but it will not be executed when import ed into other modules. Examples are as follows:

practice module:

print('hello world')

if __name__=='__main__':
    print('good morning')

Direct execution:

hello world
good morning

test module:

import parctice

Execute test module:

hello world

You can see that two lines are output during direct execution and one line is output during call execution. It indicates that the part within the if judgment condition is not executed when the call is executed. Explain that the part within the judgment conditions is not tenable.

(2)if __name__ == '__main__' Working principle of

Each python module contains built-in variables__ name__, When the module is executed directly__ name__ Equal to the file name (including the suffix. py); When import ing to other modules for execution__ name__ Equal to the name of the called module (excluding the suffix. py).

"_main_" always points to the name of the currently executing module (including the suffix. py), and when the module is executed__ name__ == '__main__' The judgment result of is true, so it is executed; When calling execution, the judgment result is false, so it is not executed.

The specific test method can be output in the program__ name__ Check the name, which will not be repeated here.

11. python calls classes and methods of another module

(1) Under the same folder

Calling function: directly import modules or import methods

Add.py file:

print('hello world')
def add(a,b):

B.py file:

Method 1:
from Add import add

Method 2:
import Add as A

hello world

Call class: the same method, import and define the class, and use it

Add.py file:

class A:
    def __init__(self,xx,yy):
    def add(self):
        print("x and y The sum of is:%d"%(self.x+self.y))

B.py file:

from A import A


import A

(2) Under different folders

A.py file path: e: \ Python project \ winycg

B.py file: use the sys.path() method of the sys library

import sys
'''python import Module is in sys.path In order.
sys.path Is a list in which many paths are stored in the form of strings.
use A.py The function in the file needs to put its file path into sys.path in'''
import A

Note: it can be seen that the imported module has been executed once regardless of the import method or the whole module directly, that is, the contents of the module are output. Therefore, generally, the module to be imported is only used as a function module, in which various methods are written for calling, rather than the actual operation.

12. Generator yield

Generator yield: yield can be understood as a return. A function with a generator is called a generator function. When the generator function is called and meets yield, the generated value is returned from this step, and the original function is returned to continue execution. The next time the generator function is called, it will be executed from the last returned place without starting from the beginning.

(1) A function with yield is a generator, which is different from a function. Generating a generator looks like a function call, but it will not execute any function code. It will be executed only when next is executed in the for loop;

(2) The execution process is still executed according to the function execution process, but each execution of a yield statement will be interrupted and an iteration value will be returned. The next execution will be executed from the next yield statement;

(3) It looks like the function is interrupted several times by yield during execution, and each interrupt will return the current iteration value through yield;


def fib(max):
    n,a,b = 0,0,1
    while n < max:
       yield b
       a,b = b,a+b
       n += 1

f = fib(6)
for i in f:


The generator saves more storage space, faster response speed and more flexible use. The common writing method is to generate all and then process them. The generator is to generate one, use one, and then delete it immediately.

Topics: Python