Python basic study notes 06-unpacking exchange variable data types lambda expression higher-order functions

1. Unpacking

Tuple:

def func(a,b):
    return a,b
num1 , num2 = func(10,20)

dictionary:

dict1 = {
    
    '姓名':'Ray','年龄':18}
key1 , key2 =dict1
print(key1)
print(key2)		# 拆包得到的是key值
print(dict1[key1])
print(dict1[key2])
# 姓名
# 年龄
# Ray
# 18

2. Exchange variables

a = 10
b = 20
a,b = b,a

3. Data Type

The data can be modified directly, if it can, it is a variable type, if not, it is an immutable type.
Variable type: List dictionary collection.
Immutable type: integer floating-point string tuple

4. Lambda expression

If a function has a return value and only one code, you can use lambda to simplify the
syntax: function name = lambda parameter list: expression
Note:
The parameters of the lambda expression are optional, and the parameters of the function are fully applicable in the lambda expression
A lambda expression can accept any number of parameters but can only return the value of an expression

fn1 = lambda a,b,c=100:a+b+c    # 默认参数
fn2 = lambda *args : args       # 可变参数
fn3 = lambda **kwargs : kwargs  # 可变参数
func = lambda a,b : a if a>b else b		# 带判断的表达式

Dictionary data sorting:

students = [
    {
    
    'name':'Tom','age':20},
    {
    
    'name':'Jerry','age':22},
    {
    
    'name':'Ray','age':24}
]
students.sort(key = lambda s:s['name'])     # 按姓名升序
students.sort(key = lambda s:s['name'],reverse = True)     # 按姓名降序

5. Higher-order functions

A function is passed in as a parameter of another function

def add_num(a,b,f):
    return f(a)+f(b)
print(add_num(10,-2,abs))

6. Built-in higher-order functions

6.1 map()
map(func,lst), apply the passed function variable func to each element of the lst variable, and compose the result into a new list

list1 = [1,2,3,4,5]
def func(x):
    return x**2
result = map(func,list1)
print(list(result))     # 需要将数据类型转化为list

6.2 reduce()
reduce(func,lst), where func must have two parameters. Each time the result of func calculation continues to be cumulatively calculated with the next element of the sequence.
Note: The parameter func passed in reduce() must receive two parameters

import functools
list1 = [1,2,3,4,5]
def func(a,b):
    return a+b
result = functools.reduce(func,list1)
print(result)   # 15

6.3 filter() The
filter(func,lst) function is used to filter the sequence, filter out elements that do not meet the conditions, and return a filter object

list1 = [1,2,3,4,5]
def func(x):
    return x%2 == 0
result = filter(func,list1)
print(list(result))

Guess you like

Origin blog.csdn.net/qq_44708714/article/details/105027277