1 lambda expression (anonymous function)
Used to represent simple functions
lambda expression, in order to solve the case of simple functions:
def func(a1,a2): =====> func = lambda a1,a2:a1+a2 # The function gets the return value directly, where the return is hidden return a1+a2 Simplify
# Triple operation, in order to solve the simple case of if else, such as: if 1 == 1: a = 123 else: a = 456 a = 123 if 1 == 1 else 456 # lambda expression, in order to solve the case of simple functions, such as: def func(a1,a2): return a1 + 100 func = lambda a1,a2: a1+100
func1 = lambda : 100 func2 = lambda x1: x1 * 10 func3 = lambda *args,**kwargs: len(args) + len(kwargs) DATA = 100 func4 = lambda a1: a1 + DATA v = func4(1) print(v) DATA = 100 def func(): DATA = 1000 func4 = lambda a1: a1 + DATA v = func4(1) print(v) func() func5 = lambda n1,n2: n1 if n1 > n2 else n2 v = func5(1111,2) print(v)
The lambda expression can only represent a function in one line, and can only use parameters as variables.
Exercises
# Exercise 1 USER_LIST = [] def func0(x): v = USER_LIST.append(x) return v result = func0('alex') print(result) # Exercise 2 def func0(x): v = x.strip() return v result = func0(' alex ') print(result) ############## Summary: All listing methods are basically returned None;All methods of strings basically return new values ################# # Exercise 3 USER_LIST = [] func1 = lambda x: USER_LIST.append(x) v1 = func1('alex') print(v1) print(USER_LIST) # Exercise 4 func1 = lambda x: x.split('l') v1 = func1('alex') print(v1) # Exercise 5 func_list = [lambda x:x.strip(), lambda y:y+199,lambda x,y:x+y] v1 = func_list[0]('alex ') print(v1) v2 = func_list[1](100) print(v2) v3 = func_list[2](1,2) print(v3)
Summary:
All methods of the list basically return None, and all methods of the string basically return new values.
2 built-in functions
Functions are divided into: custom functions and built-in functions
At present, python's built-in functions are divided into several categories:
-
1. Coercive Conversion
bool() / int() / str() / list() / dict() /tuple() / set()
-
2. Input and output
print() / input()
-
3. Other
len() / open() / id() / range() / type()
-
4. Mathematical Relevance
-
-
Absolute value of abs()
v = abs(-1) print(v) # 1
-
Converting float() to floating-point (decimal)
v = 55 v1 = float(v) print(v1) # 55.0
-
max() finds the maximum
v = [1,2,33,5,9] result = max(v) print(result) # 33
-
min() Find the minimum
v = [1,2,311,11,8] v2 = min(v) print(v2) # 1
-
sum() summation
v = [1,2,311,11,9] v1 = sum(v) print(v1) # 334
-
Quotient and remainder of divmod() dividing two numbers
a,b = divmod(1001,5) print(a,b) # 200 1
Plus: String Formatting:'Your Little Wife -% s'% (i,) - - - > Later, (i,) If there is only one variable in parentheses, it can be written as:'Your Little Wife -% s'% I.
# Exercise questions should be paginated to show the data. """ //Requirement: //Display 10 data per page //Let the user enter the page to view: page number """ USER_LIST = [] for i in range(1,836): temp = {'name':'Your Little Wife-%s' %i,'email':'123%s@qq.com' %i } USER_LIST.append(temp) # Total number of data items total_count = len(USER_LIST) # 10 items per page per_page_count= 10 # Number of total pages max_page_num,a = divmod(total_count,per_page_count) if a>0: max_page_num += 1 while True: pager = int(input('Which page do you want to see?')) if pager < 1 or pager > max_page_num: print('The page number is not valid. It must be 1. ~ %s' %max_page_num ) else: """ # Page 1: USER_LIST [0:10] - > 0123456789 # Page 2: USER_LIST[10:20] # Page 3: USER_LIST[20:30] ... """ start = (pager-1) * per_page_count end = pager * per_page_count data = USER_LIST[start:end] for item in data: print(item)
-
7.pow
pow(x,y) denotes the Y power of X
v = pow(2,3) print(v) # 8
-
8.round retains decimal places after decimal points and rounds them around.
V = round(1.127,1/2) print(v) # 1.1 / 1.13
-
-
-
5. Binary conversion correlation
-
bin() converts decimal to binary
num = 13 v1 = bin(num) print(v1) # 0b1101
-
oct() converts decimal to octal
num = 8 v1 = oct(num) print(v1) # 0o10
-
int() converts other decimal systems into decimal systems
# Converting binary to decimal v1 = '0b1101' result = int(v1,base=2) print(result) # 13 # Conversion of octal system to decimal system v1 = '0o1101' result = int(v1,base=8) print(result) # Converting hexadecimal system to decimal system v1 = '0x1101' result = int(v1,base=16) print(result)
-
hex() converts decimal to hexadecimal
num = 16 v1 = hex(num) print(v1) # 0x10
Exercises
# 1 byte equals 8 bits # IP: 192.168.12.79 -> 001010010 . 001010010 . 001010010 . 001010010 # 1. Please convert each decimal number in IP = 192.168.12.79 into binary and connect it to produce a new string. ip = "192.168.12.79" ip_list = ip.split('.') # ['192','168','12','79'] result = [] for item in ip_list: result.append(bin(int(item))) print(','.join(result)) # 2. Please convert each decimal number in IP = 192.168.12.79 into binary: # 0010100100001010010001010010001010010 - > decimal value. # 3232238671 ip = "192.168.12.79" ip1 = ip.split('.') lis = [] for i in ip1: lis.append(bin(int(i))) # val = ','.join(lis) # b = val.replace('0b', '') # b1 = b.split(',') b1 = ','.join(lis).replace('0b', '').split(',') e = [] #f or c in b1: for c in ','.join(lis).replace('0b', '').split(','): if len(c) < 8: val = 8 - len(c) d = list(c) d.insert(0,'0' * val) d1 = ''.join(d) e.append(d1) else: e.append(c) f = ''.join(e) f1 = int(f,base = 2 ) print(f1)
-
-
6. Coding correlation
-
chr converts decimal digits into corresponding strings in Unicode encoding
v = chr(65) print(v) # A
-
ord finds its decimal system in Unicode encoding based on characters
v = ord('in') print(v) # 20013
-
Application:
import random v = random.randint(65,90) print(v) # Random numbers between 65 and 90 import random data = [] for i in range(6) v = random.randint(65,90) data.append(chr(v)) print(''.join(data)) # 6-bit random string validation code import random def get_random_code(length=6): data = [] for i in range(length): v = random.randint(65,90) data.append(chr(v)) return ''.join(data) code = get_random_code() print(code) # 6-bit random string validation code
import random # Import a module v = random.randint(Start,termination) # Get a random number
-
-
7. Higher-level built-in functions
-
map loops through each element (the second parameter), then lets each element execute a function (the first parameter), saves the results of each function execution into a new list, and returns.
V1 = [11,22,33,44] # The first parameter of map(x,v1) must be a function, and the second parameter must be of iterative type (which can be cycled for) def func(arg): print(arg) # map(func,v1) # It does not print arg after execution, which is a feature of py3, which will be executed after PY3 is not executed yet. result = map(func,v1) # Then add the return value of the function to a [] # Print (result) py2 returns the list directly # Print (result) PY3 won't, it will get an object / thing, and if you want to return the list, you need to force it to be converted into a list. print(list(ruselt)) # result gets an object <map.objecta... > To print the list, you need list()
v1 = [11,22,33,44] result = map(lambda x:x+100,v1) print(list(result)) # special
-
filter
Result = filter (function, parameter)
v1 = [11,22,33,'asd',44,'xf'] def func(x): if type(x) == int: return True return False result = filter(func,v1) # [11,] print(list(result)) result = filter(lambda x: True if type(x) == int else False ,v1) print(list(result)) result = filter(lambda x: type(x) == int ,v1) print(list(result))
-
Reduc accumulates to get a result
Reduc is no longer a built-in function for py3, but it is included in py2's built-in function.
import functools v1 = ['wo','hao','e'] def func(x,y): return x+y result = functools.reduce(func,v1) print(result) result = functools.reduce(lambda x,y:x+y,v1) print(result)
-
-
8. Class-related
-
Type, view type
class Foo: pass obj = Foo() if type(obj) == Foo: print('obj yes Foo Objects of classes')
-
issubclass
Determine whether a class is a subclass of another class or its base class.
Issubclass (class 1, class 2) class 1 - > subclass name, class 2 - > base class name
class Base: pass class Base1(Base): pass class Foo(Base1): pass class Bar: pass print(issubclass(Bar,Base)) print(issubclass(Foo,Base))
-
isinstance
Determine whether an object is an instance (object) of a class or its base class
class Base(object): pass class Foo(Base): pass obj = Foo() print(isinstance(obj,Foo)) # Determine whether obj is an instance (object) of the Foo class or its base class print(isinstance(obj,Base)) # Determine whether obj is an instance (object) of the Foo class or its base class
-
super
class Base(object): def func(self): print('base.func') return 123 class Foo(Base): def func(self): v1 = super().func() print('foo.func',v1) obj = Foo() obj.func() # super().func() goes to the parent class to find the func method and executes it
class Bar(object): def func(self): print('bar.func') return 123 class Base(Bar): pass class Foo(Base): def func(self): v1 = super().func() print('foo.func',v1) obj = Foo() obj.func() # super().func() finds func methods and executes them one by one according to the inheritance relationship of the class.
class Base(object): # Base -> object def func(self): super().func() print('base.func') class Bar(object): def func(self): print('bar.func') class Foo(Base,Bar): # Foo -> Base -> Bar pass obj = Foo() obj.func() # Multiple Inheritance # super().func() finds func methods and executes them one by one according to the inheritance relationship of the class to which the self object belongs.
super(). The method to find
super().func() finds func methods one by one and executes them one by one according to the inheritance relationship of the class to which the self object belongs (from left to right).
super follows mro order to find the previous class
supper().func() is not looking for the parent class, but according to the order of mro, find their corresponding next class
-