2020_10_9_ Derivatives and functions

Derivative

The comprehension is used to quickly and conveniently generate the expression of a list or dictionary
1. List comprehension
1) Basic structure
List = [expression for variable in sequence]
generates a new list, the elements in the list correspond to each cycle The result
of the expression is equivalent to:
list = []
for variable in sequence:
list.append(expression)

list1 = [10 for x in range(3)]
print(list1) # [10, 10, 10]

list2 = [2*x for x in range(1, 4)]
print(list2) # [2, 4, 6]

Exercise 1: Write a list comprehension to produce a list of elements that satisfy the following rules: str0, str3, str6, str9,...,str99

list3 = [‘str’+str(x) for x in range(0, 100, 3)]
list3 = [f’str{x}’ for x in range(0, 100, 3)]
print(list3)

2) Conditional structure
list = [expression for variable in sequence if conditional statement]

Equivalent to:
list = []
for variable in sequence:
if conditional statement:
list.append(expression)

list4 = [x for x in range(10) if x % 2]
print(list4) # [1, 3, 5, 7, 9]

list5 = [x for x in range(10) if x % 2 == 0]
print(list5) # [0, 2, 4, 6, 8]

Exercise 2: Write a list comprehension to generate a list of elements that satisfy the following rules: str1, str3, str6, str9,..., str99
Method 1:
list6 = [f'str{x}' for x in range(1, 100) if x == 1 or x% 3 == 0]
print(list6)

方法二:
list7 = [‘str1’ if x == 0 else f’str{x}’ for x in range(0, 100, 3)]
print(list7)

(Understand)
Multiple loop structure 1:
List = [Expression for variable 1 in sequence 1 for variable 2 in sequence 2]

Equivalent to:
list = []
for variable 1 in sequence 1:
for variable 2 in sequence 2:
list.append(expression)

Multiple loop structure 2:
list = [expression for variable 1 in sequence 1 for variable 2 in sequence 2 if conditional statement]
list = []
for variable 1 in sequence 1:
for variable 2 in sequence 2:
if conditional statement:
list. append(expression)

list8 = [f’{x}{y}’ for x in range(3) for y in ‘abc’]
print(list8)

2. Set comprehension
change the [] of the list comprehension into {}
a1 = {x for x in'hello'}
print(a1) # {'o','e','l','h'}

3. Tuples and Dictionary Derivatives
Tuples-turn the [] of the list comprehension into a tuple()
dictionary-(the expression is in the form of key-value pairs) change the [] of the list comprehension into {}; (the expression is When there are only two elements in the sequence) change the [] of the list comprehension into dict()
a2 = tuple(x*2 for x in'hello')
print(a2) # ('hh','ee' ,'ll','ll','oo')

a3 = {x: x*2 for x in ‘hello’}
print(a3) # {‘h’: ‘hh’, ‘e’: ‘ee’, ‘l’: ‘ll’, ‘o’: ‘oo’}

a4 = dict((x, x*2) for x in ‘hello’)
print(a4)

Exercise 3: Exchange the keys and values ​​of a dictionary through dictionary
comprehension dic = {'a': 10,'b': 20,'c': 30} -> {10:'a', 20:'b', 30:'c'}
dic = {'a': 10,'b': 20,'c': 30}
dic1 = {dic[key]: key for key in dic}
print(dic1) # {10: ' a', 20:'b', 30:'c'}

Exercise 4: Exchange the keys and values ​​of a dictionary through dictionary comprehension. If the value is variable, do not exchange
dic = {'a': 10,'b': 20,'c': 30, ' in the new dictionary d': [10, 20]}
type(data) == list/type(data) == dict/type(data) == set

dic2 = dict((key, dic[key]) if type(dic[key]) in (list, set, dict) else (dic[key], key) for key in dic)
print(dic2) # {10: ‘a’, 20: ‘b’, 30: ‘c’, ‘d’: [10, 20]}

num = 100
if num == 10 or num == 20 or num == 30 or num == 40:
print(’====’)

if num in (10, 20, 30, 40):
print(’!!!’)

Function basis

1. Know the function

a. What is a function A
function is an encapsulation of the code that realizes a certain function. (machine)

b. Classification of functions (who defined the function)
System functions: functions that have been defined in python and can be used directly by programmers. For example: print, input, type, chr, ord, id, max, min, sum, sored, etc. (machines already built by others).
Custom functions: defined by the programmer, and can be used by the programmer or used by others function. (Build your own machine)

2. Define the function (machine)
syntax:
def function name (parameter list):
function description document
function body

Description:

  1. def-keyword; fixed writing
  2. Function name-the programmer named it;
    requirement: identifier, cannot be a keyword
    Specification: lowercase letters, separated by _;
    see the name know the meaning (see the function name, you probably know the function of the function);
    do not use the system Function name, type name and module name
  3. ():-Fixed writing (cannot be omitted)
  4. Formal parameter list-stored in the form of'variable name 1, variable name 2, variable name 3,...';
    the function of the formal parameter is to transfer the data outside the function to the function (if the realization of the function of the function needs to provide external data, then This function requires formal parameters)
  5. Function description document-the description of the function; the essence is the comment caused by """"""
  6. Function body-one or more statements (at least one) that keep the same indentation with def;
    the code segment that implements the function

(Key) Note: The function body will not be executed when the function is defined

def func1():
print(’===================’)
list1 = [1, 2]
print(list1[10])

Example 1: Define a function to find the sum of any two numbers
def sum1(num1, num2):
"""
Find the sum of two
numbers- (function description area) :param num1: provide the first number-(parameter description )
:Param num2: Provide the second number-(parameter description)
:return: None-(return value description)
"""
print(num1+num2)

Exercise 1: Define a function to find the factorial of a number: N! = 1 2 3 4 …*N
def factorial(num):
"""
Find the factorial of a number
: param num: specified number
: return: None
“” "
s = 1
for x in range(1, num+1):
s *= x
print(f'{num}'s factorial is: {s}')

Exercise 2: Write a function to cross merge two strings'abc '
, '123
' -> a1b2c3'abc
' , '12345' -> a1b2c345'abcdef ', '1234' -> a1b2c3d4ef

def merge(str1, str2):
len1 = len(str1)
len2 = len(str2)
First cross stitch parts of the same length
​ new_str =''
​ for index in range(min(
len1 , len2)):​ new_str += str1[index] + str2[index]

Then confirm the tail
if
len1 > len2: new_str += str1[len2:]
else:
new_str += str2[
len1 :] print(new_str)

merge(‘abc’, ‘123567’)

3. Call function (using machine)

Syntax:
function name (list of actual parameters)

Description:
Function name-the function name of the function that needs to be used
()-fixed writing
Argument list-exists in the form of'data 1, data 2, data 3,...'; the
actual parameters need to be passed from outside the function To the specific data used by the function content (by default, as many formal parameters as the called function need to provide as many actual parameters)

sum1(90, 10) The
same function can be used multiple times
sum1(11.1, 22.2)

factorial(5) # The factorial of 5 is: 120
factorial(10) # The factorial of 10 is: 3628800

Function parameters

1. Positional parameters and keyword parameters
According to the actual parameter transfer method, the actual parameters are divided into two types: positional parameters and keyword parameters

1) Position parameters
exist in the form of'actual parameter 1, actual parameter 2, actual parameter 3,...', so that the actual parameter and the formal parameter correspond one to one

2) Keyword parameters
exist in the form of'formal parameter 1=actual parameter 1, formal parameter 2=actual parameter 2,...'. The position of this parameter can be changed at will

3) Mixed use of positional parameters and keyword parameters
Positional parameters must be before the keyword parameters

def func1(a, b, c):
print(f’a:{a}, b:{b}, c:{c}’)

Positional parameters
func1(10, 20, 30) # a:10, b:20, c:30
func1(30, 20, 10) # a:30, b:20, c:10

Keyword parameters
func1(a=100, b=200, c=300) # a:100, b:200, c:300
func1(b=200, c=300, a=100) # a:100, b: 200, c:300

混用
func1(10, 20, c=30) # a:10, b:20, c:30
func1(100, c=230, b=220) # a:100, b:220, c:230

func1(500, 600, a=400)
func1(a=400, 500, 600)

2. Parameter default value

When defining a function, you can directly assign default values ​​to one or more formal parameters; parameters with default values ​​can be called without parameters.

def func2(a=1, b=2, c=3):
print(f’a:{a}, b:{b}, c:{c}’)

func2() # a:1, b:2, c:3
func2(10, 20) # a:10, b:20, c:3
func2(b=200) # a:1, b:200, c:3

def func3(a, b, c=3):
print(f’a:{a}, b:{b}, c:{c}’)

func3(100, 200) # a:100, b:200, c:3
func3(100, 200, 300) # a:100, b:200, c:300

Parameters with default values ​​must be followed by parameters without default values
def func4(a, c, b=200):
print(f'a:(a), b:(b), c:(c)')

func4(1, 3) # a:1, b:200, c:3

3. Variable length parameters
If the number of parameters is uncertain when defining a function, you can use variable length parameters

1) Variable length parameter with *
Add * before the formal parameter to make this formal parameter a variable length parameter, which can accept multiple actual parameters at the same time. The essence of this parameter is a tuple, and the corresponding actual parameters passed will all become elements in this tuple. (You must use positional parameters to pass parameters)

2) Variable length parameter with **
Add ** in front of the formal parameter to make this parameter a variable length parameter, which can accept multiple actual parameters at the same time. The essence of this parameter is a dictionary (keyword parameters must be used to pass parameters, the keywords themselves are named arbitrarily)

Define a function to find the average of multiple numbers
def mean(*num):
if len(num) == 0:
print('0')
else:
print(sum(num)/len(num))

mean()
mean(10)
mean(20, 12)
mean(20, 12, 23, 23, 432, 121, 90)

def func5(*a):
print(‘a:’, a)

func5(23, 45)
func5(1, 2, 3, 4)

Here x must use positional parameters to pass parameters
def func6(x, *a):
print('a:', a,'x:', x)

func6 (20) # a: () x: 20
func6 (10, 20, 30, 40) # a: (20, 30, 40) x: 10

Here x must be passed using keyword arguments
def func7(*a, x=90):
print('a:', a,'x:', x)

func7(23, 34, 45) # a: (23, 34, 45) x: 90
func7(1, 2, 3, 4, x=100) # a: (1, 2, 3, 4) x: 100

def func8 (** num):
print (num)

func8()
func8(a=100) # {'a': 100}
func8(name='张三', age=30) # {'name':'张三','age': 30}

Interview question: func(*args, **kwargs), what is the meaning of *args, **kwargs in function func to
make function calls more flexible

def func(*args, **kwargs):
pass

func()
func(2, 3, 4)
func(a=23, b=23, c=34, d=11)
func(23, 31, a=1, b=290)

Guess you like

Origin blog.csdn.net/xdhmanan/article/details/108999763