First, anonymous function
1. Definition:
An anonymous function, by definition, refers to a class of functions or subroutines that do not need to define identifiers (function names).
2. Syntax format: Lambda parameter: expression
Lambda statement, first write the keyword lambda, before the colon is a parameter, you can have multiple, separated by commas, the right side of the colon is an expression, you need to note that there can be only one expression. Since lambda returns a function object (constructed as a function object), it is necessary to define a variable to receive.
3. Note:the lambda function can receive any number of arguments (including optional parameters) and return the value of a single expression. A lambda function cannot contain commands and cannot contain more than one expression.
4. Advantages of anonymous functions:
-When using Python to write some scripts, using lambda eliminates the process of defining a function and makes the code more streamlined.
-for some abstract functions that are not reused anywhere else, sometimes a function name is a problem, and using lambda does not have to consider naming problems.
-Using lambda at some point then the code is easier to understand
5. Application: in the built-in function max () to find the maximum value, min () to find the minimum, map () map, reduce merge, filter () filter will be used!
Simple code example:
1 salaries={2 ' Egon ': 3000,3 ' Alex ': 100000000,4 ' Wupeiqi ': 10000,5 ' Yuanhao ': 20006}7 f = lambda K: Salaries[k]8 print (f) 9 print (f (' Egon '))
Execution Result:
<function <lambda> at 0x0000000000413e18>3000
Second, built-in functions
Built-in Parameter details Https://docs.python.org/3/library/functions.html?highlight=built#ascii
1.abs () The absolute value data type must be integral type!
1 Print (ABS (1)) 2 print (ABS ( -1)) 3 Print (ABS (' a '))
Execution Result:
11Traceback (most recent): File "f:/py_fullstack_s4/day25/built-in function. py", line 3, in <module> print ( ABS (' a ')) Typeerror:bad operand type for abs (): ' Str '
2.all (Iterative object) returns a Boolean value returns True if any one of the values is not true, returns flase, and iterates when the object is empty
1 Print (All (")) 2 print (All ((1,", none,0))) 3 Print (All (i-I in range (1,10))) #从1开始取值, exclude 0
Execution Result:
Truefalsetrue
3.any (Iterative object) returns a Boolean value returns True if any one of the values is true, returning flase when the iteration object is empty
1 Print (Any (")) 2 print (Any ([none,1,2, ']))
Execution Result:
Falsetrue
4. Convert Decimal to: Bin () binary hex () hexadecimal Oct () octal
1 print (BIN) #二进制2 print (hex) #十六进制3 print (Oct) #八进制
Execution Result:
1 0b11002 0xc3 0o14
5. Data type: Int () integer, str () string, list (), tuple () tuples; dict () dictionary; set () set; Frozenset () Immutable collection
Is Judge identity, identity operation, according to ID to determine identity
1 num =1 2 s = "ADXZ" 3 L = [1,2.3,4] 4 D = {1:1, "Z": 2} 5 print (type (d)) 6 print (Type (l)) 7 print (type (s)) 8 print (num is 1) 9 d = dict (x=1,y=2,z= "3") #生成字典的另一种方式11 print (d)-S = {1,2,3,4,4,3,2,5} #集合13 print (s) + S.add ((6,7)) print (s ) F = frozenset (s) #不可变集合17 print (f) Print (type (f))
Execution Result:
1 <class ' dict ' >2 <class ' list ' >3 <class ' str ' >4 True5 {' x ': 1, ' Y ': 2, ' Z ': ' 3 '}6 {1, 2, 3, 4, 5}7 {1, 2, 3, 4, 5, (6, 7)}8 Frozenset ({1, 2, 3, 4, 5, (6, 7)}) 9 <class ' Frozenset ' >
6.bool () Judging Boolean value
1 print (bool (2>1)) 2 print (bool (2<1))
Execution Result:
1 True2 False
7.bytes () bytes bytes Specify encoding format otherwise error type () see what type of data the variable is
1 s = ' ABCDEFG ' 2 print (s) #查看字符串s3 print (type (s)) #查看字符串类型4 S1 = bytes (s,encoding= ' utf-8 ') #查看字符串类型5 print (S1)
Execution Result:
1 abcdefg2 <class ' str ' >3 B ' ABCDEFG '
8.ASCII Code conversion: Chr () ASCII conversion number converted to character; Ord () ASCII conversion character converted to digital
1 print (CHR) #根据位置找值2 print (Ord (' A ')) #根据值找位置
Execution Result:
1 Q2 65
9.callable () Determines whether it is a function, in parentheses the number of incoming function name complex () defines complex numbers
1 x = Complex (1-2j) #定义一个复数2 print (type (x)) #查看函数类型3 the real part of print ( x.real) #打印x 4 print (x.imag) #打印x imaginary Part 5 Print (callable (x)) #查看是否是函数6 7 def Test (): #定义函数8 PASS9 Print (callable (test)) #查看是否是函数
Execution Result:
1 <class ' complex ' >2 1.03-2.04 False5 True
10. Help Dir (object) to see what method the object can call, Help () directly see the function of the specific assistance information
1 a = ' hnaxhoqihcqew0 ' 2 print (dir (a)) #查看调用方法 Help () to see the details directly
Execution Result:
[' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __ getattribute__ ', ' __getitem__ ', ' __getnewargs__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __init_subclass__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __ Rmod__ ', ' __rmul__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' capitalize ', ' casefold ', ' center ', ' Count ', ' encode ', ' endswith ', ' expandtabs ', ' find ', ' format ', ' Format_map ', ' index ', ' isalnum ', ' isalpha ', ' isdecimal ', ' IsDigit ', ' isidentifier ', ' islower ', ' isnumeric ', ' isprintable ', ' isspace ', ' istitle ', ' isupper ', ' join ', ' ljust ', ' Lower ', ' lstrip ', ' Maketrans ', ' partition ', ' replace ', ' rfind ', ' rindex ', ' rjust ', ' rpartition ', ' rsplit ', ' rstrip ', ' SPL It ', ' splitlines ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill '
11.divmod (int1,int2) Two numbers do division Int1/int2; The return value is a tuple (the value that is divisible, the value of the remainder); The paging that is applied mainly to the page
1 Print (Divmod (10,2)) 2 print (Divmod (10,3))
Execution Result:
(5, 0) (3, 1)
12.enumerate ()
Enumerate function Description:
- Function prototypes: Enumerate (sequence, [start=0])
- Function: Sequence sequence data and data subscript (customizable starting value) starting with start of the recyclable sequence
- That is, for a data object that can be traversed (such as a list, tuple, or string), enumerate combines the data object into an index sequence, listing both the data and the data subscript, and outputting the result as a tuple
1 list = [' Ni ', ' Hao ', ' ma ', ' Hello ', ' world ']2-I in Enumerate (list,1): 3 print (i)
Execution Result:
(1, ' ni ') (2, ' Hao ') (3, ' ma ') (4, ' hello ') (5, ' world ')
13.hash () hash () hashing algorithm, application: Data check
Characteristics:
1, the string changes, the resulting value will change
2, as long as the algorithm is consistent, the resulting value will never change, the length will not be changed.
3, the hash value can not reverse push
1 #字符串类型2 x = "Hello" 3 y = ' Hello ' #x和y two values equal 4 print (hash (x)) 5 print (hash (y)) 6 y = ' Hellobuxaoixax ' #改变y7 print (hash (x )) 8 print (hash (y))
Execution Result:
428243675223027746842824367522302774684282436752230277468-397579801337672607
14.eval () Converts a string into an expression form to perform an operation
15.id () ID () view uniquely identifies the identity information string, the number is different than a certain length
1 >>> x =10 2 >>> y =10 3 >>> print (ID (x)) 4 1393927552 5 >>> print (ID (y)) 6 139392755 2 7 >>> x = 100000000000000000000000 8 >>> y = 100000000000000000000000 9 >>> print (ID (x)) 10 42 71625611 >>> print (ID (y)) 4271629613 >>>
#拉链 Zip ()
Zip (), put in two iterators, one by one corresponds to the re-fetch value, output in the form of tuples. No matter the number of one party, it will not be output.
L1 = [1,2,3,4,5,6]s = ' Hello ' z = Zip (l1,s) for i in Z: print (i)
Execution Result:
(1, ' H ') (2, ' e ') (3, ' l ') (4, ' l ') (5, ' O ')
The 17.sorted () sort iterates over the object to get a new return value. The return value is a list, the default is ascending; reverse = True reverses. Descending; reversed () Take the reverse, putting the cart before the horse
Sort the dictionary by default according to the dictionary key.
1 salaries={2 ' Egon ': 3 ' Alex ': 100000000, 4 ' Wupeiqi ': 10000, 5 ' Yuanhao ': 6} 7 print (Sorted ( Salaries)) #按照keys排序, compare the size of the letters from small to large 8 print (sorted (salaries,reverse = True)) #按照keys排序, and then compare the size of letters from large to small 9 print ( Sorted (Salaries,key = lambda x:salaries[x])) #按照values的值排keys的序, from small to large L = [1,2,3,4
Execution Result:
[' Alex ', ' Egon ', ' Wupeiqi ', ' Yuanhao '] [' Yuanhao ', ' Wupeiqi ', ' Egon ', ' Alex '] [' Yuanhao ', ' Egon ', ' Wupeiqi ', ' Alex ']
#reversed () Apply L = [1,2,3,45,7] #定义初始列表l1 = Reversed (l) #转换 will get a return value of print (list (L1)) #list () one value, generate a list
Execution Result:
[7, 45, 3, 2, 1]
18.max () and Min () to find the maximum and minimum values
Max (*args,key=func) key is optional. When you need to use a function to judge, add key. Min and Max are used in the same way.
1 #max和min 2 print (max (1,2,3,4,10,3)) #直接比较 3 print (min (1,2,3,4,10,3)) 4 print (Max ((1, ' a '), (1, ' B ')) 5 salaries={6< c4/> ' Egon ': 7 ' Alex ': 100000000, 8 ' Wupeiqi ': 10000, 9 ' Yuanhao ': 250010}11 def get_value (k): return salaries[k]13 print (max (salaries)) #比较keys14 print (max (salaries,key=get_value)) #原始的定义一个函数15 print (max ( Salaries,key=lambda k:salaries[k]) #使用lambda函数16 print (min (salaries,key=lambda k:salaries[k]))
Execution Result:
101 (1, ' B ') Yuanhaoalexalexyuanhao
19.map Mapping
Map (func,list)
map () is a Python built-in high-order function that receives a function func and a list, and then, by putting the function f on each element of the list in turn, gets a new list and returns.
1 #map The map takes the elements of the original iteration object one after the other, returns a new iterator object 2 L = [1,2,3,45,7]3 m = map (lambda item:item*2,l) 4 print (m) 5 print (list (m))
Execution Result:
<map object at 0x00000000026e96a0>[2, 4, 6, 90, 14]
20.reduce merging rules to calculate multiple parameters! Subtraction
Reduce (fun,list, initial value) reduce the number in the list to the fun calculation note that the fun must be an operation between two numbers, the list must be an integer number, the initial value can be defined, or it can be undefined.
reduce () The function Func passed in must receive two parameters, and reduce () calls the function Func repeatedly on each element of the list and returns the final result value.
From functools Import Reducel = range (+) print (reduce (lambda x,y:x+y,l)) print (Reduce (lambda x,y:x+y,l,100))
Execution Result:
49505050
The 21.filter () filter will have a judgment that the output is a Boolean value that will filter the Boolean value to True.
Filter (function func, Iteration object list)
The filter () function receives a function func and a list, the function of which f is to judge each element, return True or False, filter() automatically filter out the non-conforming elements according to the result of the judgment. Returns a new list that is composed of qualifying elements.
1 #filter Filter 2 name_l =[3 {"name": ' Egon ', ' Age ': +}, 4 {"Name": "FSW", "Age": 5} Age ': +}, 6 {' name ': ' Jie ', ' age ': + 7] 8 F = filter (lambda d:d[' age ']>100,name_l) 9 for i in F:10 print (i)
Execution Result:
{' name ': ' Egon ', ' Age ': 120} {' name ': ' FSW ', ' Age ': 1000} {' name ': ' Wang ', ' Age ': 2000}
23. Other
POW () Two values, three values are the first two, then the value and the third number are then taken to the remainder
Round () with a decimal point value, four six into five left double ...
Slice () Defining a Slice Object
VARs () #局部变量
_import_ (' string ') converts the imported string into a module
1 #其他 2 3 #pow () 4 print (POW (3,2)) 5 print (POW (3,2,2)) 6 7 #round () Five homes six into 8 print (round (10.3)) 9 Print (Round (10.5)) Print (round (10.6)) print (round (10.9)) 17 # Slice Slice l=[1,2,3,4,5,6,7,9]15 print (L[2:5:2]) S=slice (2,5,2 Print (L[s]) #vars () is equivalent to local variable print (VARs () is locals ()) #_import_ () custom module Import Time24 # time.sleep (3) 25 Print (time) m=__import__ (' time '), print (m) m.sleep (3)
Execution Result:
9110101111[3, 5][3, 5]true<module ' time ' (built-in) ><module ' time ' (built-in) >
# #在面向对象里讲
# Classmethod
# Staticmethod
# property
#
# delattr
# hasattr
# GetAttr
# SetAttr
#
# Issubclass
#
# super
Python anonymous functions and built-in functions