Built-in function supplement
python Divmod () function: combine the results of divisor and remainder operations to return a tuple containing quotient and remainder (A//b, a% b)
Grammar:
1 Divmod (A, b) #a, B is a number, a is a divisor and B is dividend
Example:
1 >>> divmod (7, 2) 2 (3, 1) #3为商, 1 is the remainder 3 >>> divmod (7, 2.5) 4 (2.0, 2.0)
Application: Web Front end page Count
1 total_count=732 per_count=233 res=divmod (total_count,per_count) 4 if res[1] > 0:5 page_count=res[0]+16 Print ( Page_count)
Enumerate () function: used to combine a data object that can be traversed (such as a list, tuple, or string) into an index sequence, while listing data and data subscripts, typically used in a for loop.
Grammar:
1 Enumerate (sequence, [start=0]) 2 # sequence--a sequence, iterator, or other supporting Iteration Object 3 # Start--Subscript start position
Example:
1 l=[' A ', ' B ', ' C ']2 for I in Enumerate (l): 3 print (i) 4 output result: 5 (0, ' a ') 6 (1, ' B ') 7 (2, ' C ')
Frozenset () function: Returns a frozen collection that freezes after the collection can no longer add or remove any elements
Grammar:
1 Frozenset ([iterable]) #iterable为可迭代对象
Example:
1 >>> dir (set) #包含add, clear, pop, remove and other modification methods 2 [' __and__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __gt__ ', ' __hash__ ', ' __iand__ ', ' __init__ ', ' __ Init_subclass__ ', ' __ior__ ', ' __isub__ ', ' __iter__ ', ' __ixor__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __ne__ ', ' __new__ ', ' __ Or__ ', ' __rand__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __ror__ ', ' __rsub__ ', ' __rxor__ ', ' __setattr__ ', ' __ Sizeof__ ', ' __str__ ', ' __sub__ ', ' __subclasshook__ ', ' __xor__ ', ' Add ', ' clear ', ' copy ', ' Difference ', ' Difference_ Update ', ' Discard ', ' intersection ', ' intersection_update ', ' isdisjoint ', ' issubset ', ' issuperset ', ' Pop ', ' Remove ', ' Symmetric_difference ', ' symmetric_difference_update ', ' Union ', ' Update ']3 >>> dir (frozenset) # Freezing does not contain any modifiable methods 4 [' __and__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' _ _ge__ ', ' __getattribute__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __init_subClass__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __ne__ ', ' __new__ ', ' __or__ ', ' __rand__ ', ' __reduce__ ', ' __reduce_ ' Ex__ ', ' __repr__ ', ' __ror__ ', ' __rsub__ ', ' __rxor__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __sub__ ', ' __ Subclasshook__ ', ' __xor__ ', ' Copy ', ' difference ', ' intersection ', ' isdisjoint ', ' issubset ', ' issuperset ', ' symmetric_ ' Difference ', ' union ']5 6 S=frozenset ({})
Globals () function: returns all global variables of the current position as dictionary type, corresponding to locals () returns the local variable of the current position
Grammar:
1 Globals ()
Example:
1 >>> Globals () 2 {' __name__ ': ' __main__ ', ' __doc__ ': None, ' __package__ ': None, ' __loader__ ': <class ' _frozen _importlib. Builtinimporter ', ' __spec__ ': None, ' __annotations__ ': {}, ' __builtins__ ': <module ' builtins ' (built-in) >}3 & Gt;>> Locals () 4 {' __name__ ': ' __main__ ', ' __doc__ ': None, ' __package__ ': None, ' __loader__ ': <class ' _frozen_ Importlib. Builtinimporter ', ' __spec__ ': None, ' __annotations__ ': {}, ' __builtins__ ': <module ' builtins ' (built-in);}
Hash () function: used to get a hash of an object (string or numeric value, etc.)
Grammar:
1 hash (object) immutable types #对象可以是数字, strings, tuples, and so on
Example:
1 >>> hash (' test ') 2-28192874772036538053 >>> Hash ((4)) 2528502973977326415
isinstance () function: to determine whether an object is a known type, similar to type ()
Grammar:
1 Isinstance (object, ClassInfo) 2 #object--instance object. 3 #classinfo--can be either a direct or indirect class name, a primitive type, or a tuple with them.
Example:
1 >>> isinstance (1,int) 2 True3 >>> isinstance (1, (int,float,list)) #类型可以用一个元组包含多个, Returns TRUE4 True as long as there is a match on it
iter () function: used to build iterators
Grammar:
1 iter (object[, Sentinel]) 2 # Object--the collection objects that support iterations 3 # Sentinel--If the second argument is passed, the parameter object must be a callable object (for example, a function), at which time ITER creates an iterator Object that is invoked every time the __next__ () method of the iterator object is called.
Example:
1 for I in ITER ([]): #[1,2,3].__iter__ () 2 print (i) 3 output result: 4 15 26 3
pow () function: returns the value of XY (x's y-square)
Grammar:
1 pow (x, y[, z]) 2 #函数是计算x的y次方, if z is present, then the result is modeled and the result is equivalent to POW (x, y)%z
Example:
1 >>> Pow (5,2,2) #计算5的2次方的2的余数2 1
range () function: You can create a list of integers that are typically used in a for loop
Grammar:
1 range (Start, stop[, step]) 2 #start: Count starts from start. The default is starting from 0. For example, range (5) is equivalent to range (0, 5), 3 #end: Count to end, but do not include end. For example: Range (0, 5) is [0, 1, 2, 3, 4] No #step: Step, default is 1. Example: Range (0, 5) is equivalent to range (0, 5, 1)
Example:
1 for I in Range (0,5,2): #0 2 Print (i) 3 for I in Range (5,0,-1): #反向取4 Print (i)
reverse () function: used to reverse the elements in a list
Grammar:
1 List.reverse ()
Example:
1 >>> l1=[3,5,1,2]2 >>> list (reversed (L1)) 3 [2, 1, 5, 3]4 >>> reversed (L1) #本身是个迭代器5 <l Ist_reverseiterator Object at 0x0000023ca11e3d30>
round () function: Returns the rounding value of a floating-point number
Grammar:
1 round (x [, n]) #x为浮点数, n is rounding the number of digits
Example:
1 >>> round (80.23456, 2) 2 80.233 >>> round (100.0010056, 3) 4 100.0015 >>> round (-100.0030056, 3 ) 6-100.003
Slice () function: Returns a Slice object that is mainly used for parameter passing in the slice manipulation function
Grammar:
1 slice (start, stop[, Step)) 2 #start--Start position 3 #stop--End position 4 #step--pitch, step
Example:
1 >>> l=[' A1 ', ' A2 ', ' A3 ', ' A4 ', ' A5 ', ' A6 ', ' A7 ', ' A8 ', ' A9 ']2 >>> l[2:5:2]3 [' A3 ', ' A5 ']4 >>> x= Slice (2,5,2) 5 >>> l[x]6 [' A3 ', ' A5 ']
sorted () function : Sorts all objects that can be iterated, producing a new object that does not take effect on the original object
Grammar:
1 sorted (iterable[, cmp[, key[, Reverse]]) 2 #iterable--can iterate over objects. 3 #cmp--The function of comparison, this has two parameters, the value of the parameter is taken out from the iterator object, the function must obey the rule is, greater than the return 1, less than the return-1, equal to return 0. 4 #key--mainly for the comparison of elements, only one parameter, the specific function of the parameters are taken from the object can be iterated, the object can be iterated to specify an element to sort. 5 #reverse--collation, reverse = True descending, reverse = False Ascending (default).
Example:
1 >>> l=[1,2,4,9,-1]2 >>> sorted (L) #从小到大3 [-1, 1, 2, 4, 9]4 >>> sorted (l,reverse=true) #从大到小 5 [9, 4, 2, 1,-1]
sum () function: sums the series
Grammar:
1 sum (iterable[, start]) 2 #iterable--can iterate over objects, such as lists. 3 #start--Specify the parameters for the addition, and if not set, the default is 0.
Example:
1 >>> sum ([0,1,2]) 2 >>> sum ((2, 3, 4), 1) # tuple calculates the sum followed by the addition of the sum ([0,1,2,3,4], 2)
# List calculates the sum and then adds 26 12
The Zip () function: is used for iterating over an object as an argument, wrapping the corresponding element in an object into a tuple, and then returning a list of those tuples.
If the number of elements of each iterator is inconsistent, the returned list is the same length as the shortest object, and the * operator allows you to extract the tuple as a list
Grammar:
1 zip ([iterable, ...]) #一个或多个迭代器, the zip function returns an iterator
Example 1:
1 s= ' Hello ' 2 l=[1,2,3]3 for I in Zip (s,l): 4 print (i) 5 output result: 6 (' H ', 1) 7 (' E ', 2) 8 (' L ', 3)
Example 2:
1 s= ' Hello ' 2 l=[1,2,3]3 zipped = Zip (s,l,) # Pack as a list of tuples 4 for x in Zip (*zipped): # Contrary to zip, can be understood as decompression, return two-dimensional matrix 5 print (x)
anonymous functions
anonymous function, which is a function without a name.
The famous function uses the DEF definition, called by the function name, and the anonymous function is defined by a lambda definition, either directly or by a person specifying a function name.
For example, define a function that returns the square of a value, defined by the following function:
1 def func1 (x): 2 return x**23 print (FUNC1 (5))
anonymous function definitions:
1 Func=lambda x:x**2 #x为函数接收的值, x**2 equivalent to the return x**22 print (func (5)) of the famous function
Other examples:
1 F1=lambda x,y:x+y 2 print (F1) #返回值为33 #4 f2=lambda x:x>15 Print (F2 (3)) #返回值为True
anonymous function If you do not specify a name, then after the definition is deleted in memory, so the anonymous function is generally used only once, mainly in the built-in functions Max, Min, map, reduce and filter.
max () function: returns the maximum value of a given parameter, which can be a sequence, and Max is similar to a for loop, traversing
Grammar:
1 max (x, y, Z, ....) [Key]) #key为比较的值类型, is a function
Example:
>>> Max ( -20, 400>>> max) ( -80, -20, -10) -10>>> max (0, +, -400) 100>>> Max (' ABC ', ' BCD ', ' aaa ') #字符串比较大小是根据字母顺序, the farther back the bigger. Compare the first character, if the first character, the second one, then ' BCD '
Combined with anonymous function application:
1 #普通方法: The name of the person who output the highest wage 2 salaries={3 ' Egon ': 5, 4 ' Alex ': The 100000000, and the Yuanhao ' Wupeiqi ': 10000 6 : 7} 8 9 print (max (salaries)) #比较的是名字字符串的大小, the output is the name Salaries.values (Max ())) #比较的是工资大小, The output is the number of payroll res=zip (Salaries.values (), Salaries.keys ()) #拉链函数将key和value做成元组12 print (max (res) [1]) # Compare the 0 index position of the tuple, output index position 1 value 13 output: yuanhao15 10000000016 alex17 18 #=========== Split line June ============19 # Combined with lambda application: output the highest wage person's name salaries={21 ' Egon ': 3000,22 ' Alex ': 100000000,23 ' Wupeiqi ': 10000,24 ' Yuanhao ': 200025}26 #def func (x): #定义函数, outputs the value of a key by # return salaries[x]28 print (max (Salaries,key=lambda x: SALARIES[X]) #key是指定一个函数作为比较对象, the default comparison is the size of the dictionary key, the return value of the lambda becomes the corresponding value of the comparison
min () function: returns the minimum value of a given parameter, which can be a sequence, similar to how Max is used
Grammar:
Slightly
Example:
Slightly
map () function: The specified sequence is mapped according to the provided function
The first parameter function calls a function function with each element in the parameter sequence, returning a new list containing the return value of each function.
Grammar:
1 map (function, iterable) 2 #function--function 3 #iterable--one or more sequences
Example 1:
1 l=[1,2,3,4]2 m=map (lambda x:x**2,l) 3 print (list (m)) 4 output result 5 [1, 4, 9, 16]
Example 2:
names=[' Bob ', ' Natasha ', ' Lisa ']print (list (map (lambda item:item+ ' _sb ', names))) output results [' BOB_SB ', ' natasha_sb ', ' LISA_SB ‘]
reduce () function: merges elements in the parameter sequence.
The function uses all the data in a data collection (linked list, tuple, and so on) to perform the following operations on the function function (with two parameters) passed to reduce, which first operates on the 1th and 2 elements of the set, and the resulting results are then calculated with the third data using the functions, and finally a result is obtained.
Grammar:
1 reduce (function, iterable[, initializer]) 2 #function--function 3 #iterable--can iterate over object 4 #initializer--optional, initial parameter
Example:
1 #普通方法实现0-100 (excluding 100) and 2 res=0 3 for I in range: 4 res+=i 5 Print (res) 6 7 #============== split line June ============= 8 from Functools Import reduce 9 #reduce方法实现0-100 and added default value of (Reduce (lambda x,y:x+y,range (100), 100))
The filter () function: used to filter the sequence, filter out elements that do not meet the criteria, and return a new list of eligible elements.
The two parameters are received, the first is a function, the second is a sequence, each element of the sequence is passed as a parameter to the function, and then returns True or False, and finally the element that returns true is placed in the new list.
Grammar:
1 Filter (function, iterable) 2 #function--judgment function. 3 #iterable--can iterate over objects
Example:
1 names=[' bob_sb ', ' natasha_sb ', ' lisa_sb ', ' Egon ']2 print (list (filter (Lambda name:name.endswith (' _sb '), names)) #筛选出 _SB end of element 3 output result 4 [' BOB_SB ', ' natasha_sb ', ' LISA_SB ']
Recursive functions
Recursive invocation: In the process of invoking a function, the function itself is called directly or indirectly
Call directly:
1 def func (): 2 print (' ====>func ') 3 func () 4 func () 5 #会陷入死循环报错, default recursive level limit, can be changed
Indirect invocation:
1 def foo (): 2 print (' from foo ') 3 Bar () 4 def Bar (): 5 print (' from Bar ') 6 foo () 7 foo () 8 #会陷入死循环报错, Default recursive level limit, can be changed
Example 1: Calculating age
1 def Age (n): 2 if n = = 5:3 return 184 return age (n+1) +25 print (age (1))
There are two procedures for recursive functions: recursion and backtracking
The recursive process requires a breakpoint, the If judgment in Example 1, which, if there is no break point, will fall into a dead loop, causing a memory overflow
Backtracking returns the evaluation from the breakpoint
Example 2:
1 l=[1,[2,3,[4,5,[6,7,[8,9,[10,11,[12,13]]]]]]]2 def func (L): 3 for i in L:4 if Isinstance (i,list): 5 func ( i) 6 else:7 Print (i) 8 func (L)
Python-based built-in function additions, anonymous functions, recursive functions