python entry level

Anonymous function (lambda)

        Lambda can define an anonymous function. An anonymous function is a function without a function name. For example, the functions we define with def have function names, while functions defined with lambda do not need function names, as long as there is the operation logic in the function. Lambda can only have one line of logic when defining an anonymous function, so the anonymous function defined by lambda is usually an expression, just like a macro in C++. But lambda can also define anonymous functions with complex logic. We only need to put a complex function in the expression. Lambda is often used in conjunction with higher-order functions map and filter.

basic structure

lambda 形参1, 形参2, ..., 形参n: 运算逻辑表达式

Write the formal parameter name directly after lambda, without writing the function name. Use a colon directly after writing the formal parameters. Define the operation logic expression after the colon. The expression must be written in this line. It cannot be broken into new lines but can be divided into multiple lines using \. So the difference between lambda and def is that the function name must be defined after def, and the formal parameters must be placed in parentheses. The function defined by def can have multiple lines of operational logic expressions.

anonymous = lambda a, b: a + b  # 使用lambda定义一个匿名函数,并赋值给变量anonymous
print(anonymous(1, 1))  # 执行 1 + 1
print(anonymous(5, 1))  # 执行 5 + 1

The execution results are as follows:

So lambda a, b: a + b is equivalent to the following function:

def add(a, b):
    return a + b


anonymous = add
print(anonymous(1, 1))  # 执行 1 + 1
print(anonymous(5, 1))  # 执行 5 + 1

We can also write some other expressions in lambda, for example, to process strings and capitalize the first letter of each string.

anonymous = lambda x: x.capitalize()
print(anonymous('hello'))
print(anonymous('world'))

The execution results are as follows:

Delayed execution of functions

        Putting the executed function in the logical expression of lambda can delay the execution of the function that should be executed. It is equivalent to adding a layer of functions outside the executed function. When the outer function is not executed, the inner function cannot be executed.

def people_info(name, sex, age):
    """
    返回对应的人物信息

    :param name: 姓名
    :param sex: 性别
    :param age: 年龄
    :return: 人物信息
    """
    print('开始执行people_info函数')
    if sex not in ['男', '女']:
        return '性别输入错误,请输入正确的性别男或者女'
    adult = {'男': '先生', '女': '女士'}
    minor = {'男': '小弟弟', '女': '小妹妹'}
    if age >= 18:
        return f'{name}{adult[sex]}今年{age}岁'
    else:
        return f'{name}{minor[sex]}今年{age}岁'


anonymous = lambda: people_info('小明', '男', 23)
print('开始执行匿名函数')
print(anonymous())

The execution results are as follows:

From the execution results, we can see that the anonymous function needs to be executed first before the people_info function is executed. This is similar to a closure function. As long as the outer anonymous function is not executed, the inner people_info function will not be executed. In this way, we can turn an executing function into a to-be-executed function. It can be used in some trigger events that need to be bound to execution functions, and can also be used to simplify some closure functions.

Built-in higher-order functions

map()

        The map function receives two parameters, the first parameter is a function, and the second parameter is an iterable object. map will return an iterator that can apply the passed function to each element of the iterable object in turn. We can use the next function to let the generator execute one after another. Calling the next function iterator in sequence will apply the function to one element until all elements have been applied. Now we don’t understand iterators or the next function. It doesn’t matter. We know that the for loop will automatically use the next function. We can just use the for loop.

def add_postfix(name: str):
    """
    给文件添加后缀

    :param name: 文件名
    :return:
    """
    return name + '.txt'


novel_list = ['百练成仙', '斗破苍穹', '求魔', '遮天', '凡人修仙传']
for i in map(add_postfix, novel_list):
    print(i)

The execution results are as follows:

We can see that each element in the list novel_list has been processed by the add_postfix function, and each novel has the suffix .txt added.

        The list function can turn an iterator into a list, so we can also use the list function to process the map function.

def add_postfix(name: str):
    """
    给文件添加后缀

    :param name: 文件名
    :return:
    """
    return name + '.txt'


novel_list = ['百练成仙', '斗破苍穹', '求魔', '遮天', '凡人修仙传']
novel_list = list(map(add_postfix, novel_list))
print(novel_list)

The execution results are as follows:

combined lambda

        For simple logic like adding a suffix to a file, using lambda will make it easier and shorten the code.

novel_list = ['百练成仙', '斗破苍穹', '求魔', '遮天', '凡人修仙传']
novel_list = list(map(lambda name: name + '.txt', novel_list))
print(novel_list)

The execution results are as follows:

filter()

        The filter function receives two parameters, the first parameter is a function, and the second parameter is an iterable object. filter will return an iterator that can apply the passed function to each element of the iterable object in turn. But unlike map, filter will filter based on the true or false return value of the function, leaving only elements with a true return value. We can use the next function to let the iterator execute one after another. Calling the next function generator in sequence will apply the function to one element until all elements have been applied. Just like the map function, we can just use a for loop.

def judge_odd(number: int):
    """
    判断奇数

    :param number: 整数
    :return: bool
    """
    if number % 2 > 0:
        return True
    return False


number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in filter(judge_odd, number_list):
    print(i)

The execution results are as follows:

From the execution results, we can see that all odd numbers are retained, while even numbers are filtered out.

        The list function can turn an iterator into a list, so we can also use the list function to process the filter function.

def judge_odd(number: int):
    """
    判断奇数

    :param number: 整数
    :return: bool
    """
    if number % 2 > 0:
        return True
    return False


number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
number_list = list(filter(judge_odd, number_list))
print(number_list)

The execution results are as follows:

combined lambda

        For simple logic like filtering odd numbers, it is easier to use lambda directly.

number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
number_list = list(filter(lambda x: x % 2 > 0, number_list))
print(number_list)

The execution results are as follows:

ternary operator (if else)

变量 = 对象1 if 条件 else 对象2

        The if else statement written in one line can be used as an operator, called the ternary operator, and its operation logic is exactly the same as the logic of if else. When the condition after if is met, variable = object 1; when the condition after if is not met, variable = object 2.

name = "爆笑蛙" if 2 > 1 else "小明"
print(name)

Because the 2 > 1 condition is true, the value of name is 'Funny Frog'. The execution results are as follows:

You can also change the condition to 2 < 1 to see if the value of name is 'Xiao Ming'.

Generative

        There are three generation types in Python: list generation, set generation, and dictionary generation. They can effectively simplify our code and turn statements that require multiple lines of code into one line of statements.

List expression

list1 = [表达式 for循环语句 if条件语句]

        List generation can generate a list according to a certain logic, continuously output the value through the for loop, then apply the value to the expression operation, and then pass the operation result to the if conditional statement to determine whether the operation result should be kept in the list. The if conditional statement is not necessary and can be omitted when no conditional judgment is required. An expression is a piece of operational logic, which can be just a variable, a lambda anonymous function, direct call to other functions, or operational logic using various operators.

Single level for loop

        When there is no nested for loop in the for loop statement, the logic is relatively simple and easy to understand, which is suitable for us to initially understand the list generation formula.

list1 = [i for i in range(10)]
print(list1)

The execution results are as follows:

From the execution results, we can find that the list generation puts all the values ​​iterated by the for loop into the list. Equivalent to the following code:

list1 = []
for i in range(10):
    list1.append(i)
print(list1)

This method requires 3 lines of code to do, but list generation can be done in one line.

Multi-level for loop

        There are one or more levels of for loops nested in the for loop. Multiple levels of for loops are written in one line, which requires some logical thinking to understand.

surname = ['赵', '钱', '孙', '李']
name = ['三', '四', '五']
list1 = [i + n for i in surname for n in name]
print(list1)

The execution results are as follows:

From the execution results, we can see that the first for loop is the outer for loop, and the second for loop is the inner for loop. The nesting of for loops can be written continuously, and the last for loop is the innermost for loop. Equivalent to the following code:

surname = ['赵', '钱', '孙', '李']
name = ['三', '四', '五']
list1 = []
for i in surname:
    for n in name:
        list1.append(i + n)
print(list1)

This method requires 6 lines of code to do, and the list generation method can be done in 3 lines.

Single layer if condition

        After the for loop, we can write an if judgment statement to control which results will be placed in the list.

list1 = [i for i in range(10) if i % 2 > 0]
print(list1)

The execution results are as follows:

From the execution results, we can find that i will be placed in the list only when i satisfies the condition after if, so the list is full of odd numbers. Equivalent to the following code:

list1 = []
for i in range(10):
    if i % 2 > 0:
        list1.append(i)
print(list1)

This method requires 4 lines of code to do, and list generation can be done in one line.

Union ternary operator

        Use the ternary operator in expressions to add more options.

list1 = [i if i > 5 else 1 for i in range(10)]
print(list1)

The execution results are as follows:

Through the ternary operator, we can change the value of some results. Equivalent to the following code:

list1 = []
for i in range(10):
    if i > 5:
        list1.append(i)
    else:
        list1.append(1)
print(list1)

This method requires 6 lines of code to do, and list generation can be done in one line.

set production

set1 = {表达式 for循环语句 if条件语句}

        Set generation can generate a set according to a certain logic, continuously output values ​​through a for loop, then apply the value to the expression operation, and then give the operation result to the if conditional statement to determine whether the operation result should be kept in the set. The if conditional statement is not necessary and can be omitted when no conditional judgment is required. An expression is a piece of operational logic, which can be just a variable, a lambda anonymous function, direct call to other functions, or operational logic using various operators.

Single level for loop

        When there is no nested for loop in the for loop statement, the logic is relatively simple and easy to understand, which is suitable for us to initially understand the set generation.

set1 = {i for i in 'abcdefghij'}
print(set1)

The execution results are as follows:

From the execution results, we can see that the set generation puts all the values ​​iterated by the for loop into the set. Equivalent to the following code:

set1 = set()
for i in 'abcdefghij':
    set1.add(i)
print(set1)

This method requires 3 lines of code to do, and the collection generation can be done in one line.

Multi-level for loop

        There are one or more levels of for loops nested in the for loop. Multiple levels of for loops are written in one line, which requires some logical thinking to understand.

set1 = {i.upper() + n for i in 'abc' for n in 'uvw'}
print(set1)

The execution results are as follows:

From the execution results, we can see that the first for loop is the outer for loop, and the second for loop is the inner for loop. The nesting of for loops can be written continuously, and the last for loop is the innermost for loop. Equivalent to the following code:

set1 = set()
for i in 'abc':
    for n in 'uvw':
        set1.add(i.upper() + n)
print(set1)

This method requires 4 lines of code to do, and the set generation can be done in one line.

Add if conditional statement

        After the for loop, we can write an if judgment statement to control which results will be placed in the collection.

set1 = {i for i in 'abcdefghij' if i > 'e'}
print(set1)

The execution results are as follows:

From the execution results, we can find that i will be placed in the set only when i satisfies the condition after if, so the set is full of strings greater than 'e'. Equivalent to the following code:

set1 = set()
for i in 'abcdefghij':
    if i > 'e':
        set1.add(i)
print(set1)

This method requires 4 lines of code to do, and the set generation can be done in one line.

Union ternary operator

        Use the ternary operator in expressions to add more options.

set1 = {i if i > 'e' else i.upper() for i in 'abcdefghij'}
print(set1)

The execution results are as follows:

Through the ternary operator, we can change the value of some results. Equivalent to the following code:

set1 = set()
for i in 'abcdefghij':
    if i > 'e':
        set1.add(i)
    else:
        set1.add(i.upper())
print(set1)

This method requires 6 lines of code to do, and the set generation can be done in one line.

dictionary generation

dict1 = {得到键值对的表达式 for循环语句 if条件语句}

        Dictionary generation can generate a dictionary according to a certain logic, continuously output values ​​through a for loop, and then apply the values ​​​​to the expression operation, and then give the operation results to the if conditional statement to determine whether to keep the operation results in the dictionary. The if conditional statement is not necessary and can be omitted when no conditional judgment is required. An expression is a piece of operational logic, which can be just a variable, a lambda anonymous function, direct call to other functions, or operational logic using various operators.

Single level for loop

        When there is no nested for loop in the for loop statement, the logic is relatively simple and easy to understand, which is suitable for us to initially understand the dictionary generation.

dict1 = {key: value for key, value in [['数学', 99], ['语文', 89], ['英语', 85]]}
print(dict1)

The execution results are as follows:

From the execution results, we can see that the dictionary generation puts all the values ​​iterated by the for loop into the dictionary. Equivalent to the following code:

dict1 = {}
for key, value in [['数学', 99], ['语文', 89], ['英语', 85]]:
    dict1[key] = value
print(dict1)

This method requires 3 lines of code to do, and the dictionary generation can be done in one line.

Multi-level for loop

        There are one or more levels of for loops nested in the for loop. Multiple levels of for loops are written in one line, which requires some logical thinking to understand.

dict1 = {f'{i}_{n}': n for i in 'abc' for n in range(1, 3)}
print(dict1)

The execution results are as follows:

From the execution results, we can see that the first for loop is the outer for loop, and the second for loop is the inner for loop. The nesting of for loops can be written continuously, and the last for loop is the innermost for loop. Equivalent to the following code:

dict1 = {}
for i in 'abc':
    for n in range(1, 3):
        dict1[f'{i}_{n}'] = n
print(dict1)

This method requires 4 lines of code to do, and the dictionary generation can be done in one line.

Add if conditional statement

        After the for loop, we can write an if judgment statement to control which results will be placed in the dictionary.

dict1 = {key: value for key, value in [['数学', 99], ['语文', 89], ['英语', 85]] if value > 90}
print(dict1)

The execution results are as follows:

From the execution results, we can see that only when the value satisfies the if condition, key: value will be placed in the dictionary, so only the math scores are placed in the dictionary. Equivalent to the following code:

dict1 = {}
for key, value in [['数学', 99], ['语文', 89], ['英语', 85]]:
    if value > 90:
        dict1[key] = value
print(dict1)

This method requires 4 lines of code to do, and the dictionary generation can be done in one line.

Union ternary operator

        Use the ternary operator in expressions to add more options.

dict1 = {key: value if value < 90 else '优秀' for key, value in [['数学', 99], ['语文', 89], ['英语', 85]]}
print(dict1)

The execution results are as follows:

Through the ternary operator, we can change the value of some results. Equivalent to the following code:

dict1 = {}
for key, value in [['数学', 99], ['语文', 89], ['英语', 85]]:
    if value < 90:
        dict1[key] = value
    else:
        dict1[key] = '优秀'
print(dict1)

This method requires 6 lines of code to do, and the set generation can be done in one line.

Guess you like

Origin blog.csdn.net/qq_40148262/article/details/132029391