Today we are going to learn some of the built-in functions in Python, because more, you can generalize these functions into 7 classes, specifically as
Scope-dependent
First, let's take a look at the function related to scope ====.> get local variables and global variables in the form of a dictionary
Globals ()------Get a dictionary of global variables
Locals ()------Gets a dictionary of local variables in the namespace in which this method is executed
Other
Input/output related
Usage of input
s = input ("") # Enter content assigned to s variable print(s) # Enter what prints what. Data type is str
Input Inputs
Print output
f = open ('tmp_file','w')Print (123,456,sep=',', file = f,flush=true)
description of the file keyword
Import TimeImportSYS forIinchRange (0,101,2): Time.sleep (0.1) Char_num= I//2#How many # of printsPer_str ='%s%%:%s\n'% (I,'*'* Char_num)ifi = = 100Else '\r%s%%:%s'% (I,'*'*char_num)Print(per_str,end="', File=sys.stdout, flush=true) to implement the progress bar
Implementing the Print progress bar
Data type correlation
Type (' a ') returns the data type of the variable O
Memory-related
ID (o) o is a parameter that returns the memory address of a variable
Hash (o) O is a parameter that returns a hash value of a hash variable, and the non-hash variable will be hashed after the error.
T= (= = [n/a]print(hash (t)) # hashprint(hash (L)) # will error " Result: typeerror:unhashable type: ' list '" Hash instance
Hash Instance
Attention:
The hash function processes the current hash variable according to an internal algorithm, returning an int number.
* Each time the execution of the program, the same content of the variable hash value will not change during this time of execution.
File Operation related
Open () Opens a file that returns a file operator (file handle)
The mode of operation of the file has a total of 6 r,w,a,r+,w+,a+, each of which can be operated in binary form (rb,wb,ab,rb+,wb+,ab+)
You can specify the encoding with encoding.
Module Operation related
__import__ Importing a module
Help methods
In the console, perform help () to enter assist mode. You can enter variables or types of variables as you choose. Enter Q to exit
or directly execute Help (O), O is the parameter, view and variable o about the operation ...
Call the relevant
Callable (o), O is the parameter to see if this variable is callable.
If O is a function name, it returns true
def func ():passprint(callable (func)) # parameter is a function name, callable, returns True Print(callable (123)) # parameter is a number, not callable, returns false
Callable Instances
View all built-in methods for the type of the parameter
Dir () View the properties in the global space by default, and also accept a parameter to view the methods or variables within this parameter
Print (dir (list)) # View the built-in methods for a list Print (dir (int)) # to view the built-in methods for integers
view built-in methods for a variable/data type
Execution of the STR type code
Built-in functions Eva, exec, Complie usage
eval () executes the string type code and returns the result
Print (Eval ('1+2+3+4'))
EXEC () executes code from the string type
Print (exec("1+2+3+4")) exec ("print (' Hello,world ')")
compile compiles the code of the string type. The code object can be evaluated by EXEC statement execution or eval ().
Parameter description:
1. Parameter source: string or AST (Abstract Syntax Trees) object. That is, the code snippet that needs to be executed dynamically.
2. Parameter filename: The name of the code file, and some recognizable values are passed if the code is not read from the file. When the source parameter is passed in, the filename argument passes in a null character.
3. Parameter model: Specifies the type of compiled code that can be specified as ' exec ', ' eval ', ' single '. When the source contains a process statement, the model should be specified as ' exec '; When source contains only a simple evaluation expression, the model should be specified as ' eval '; When the source contains an interactive command statement, the model should be specified as ' single '.
>>>#The process statement uses the EXEC>>> Code1 ='For i in range (0,10): Print (i)'>>> compile1 = Compile (Code1,"','exec')>>>exec(Compile1)13579>>>#Simple evaluation expressions with Eval>>> Code2 ='1 + 2 + 3 + 4'>>> compile2 = Compile (Code2,"','Eval')>>> eval (compile2)
View Code
and number-related
Number--Data type Related: Bool,int,float,complex
Number--Binary conversion correlation: Bin,oct,hex
Numbers-mathematical operations: ABS,DIVMOD,MIN,MAX,SUM,ROUND,POW
Data structure related
Sequence--Lists and tuples Related: list and tuple
Sequence--string-Related: Str,format,bytes,bytesarry,memoryview,ord,chr,ascii,repr
Sequence: Reversed,slice
Data collection--dictionaries and collections: Dict,set,frozenset
Data collection: Len,sorted,enumerate,all,any,zip,filter,map
Add:
Use of map and filter
Map
The map function in Python is applied to each iteration of an item and returns a list of results. If other iterative parameters are passed in, the map function iterates through each parameter with the corresponding processing function. The map () function receives two parameters, one is a function, the other is a sequence, and map passes the incoming function to each element of the sequence sequentially, returning the result as a new list.
>>> L = [1,2,3,4defreturn x*>>> Map (pow2,l) [
Usage of Map
Filter
The filter () function receives a function f and a list, the function of which is to judge each element, return True or False,filter () automatically filters out the non-conforming elements according to the result of the decision, and returns a new list that is composed of qualifying elements.
Filter () to 1~100 that the square root is an integer number, i.e. the result should be:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Import Math def IS_SQR (x): return math.sqrt (x)% 1 = = 0Print filter (IS_SQR, Range (1, 101)) The result is [1, 4, 9, 16, 25, 36 , 49, 64, 81, 100]
Usage of filter
With filter (), you can accomplish many useful functions, such as deleting None or an empty string:
def Is_not_empty (s): return s and len (S.strip ()) > 0 >>>filter (is_not_empty, [ " Span style= "COLOR: #800000" >test ", None, ' , ' str ' , " , ' ])
The result is
['test'str'END']
Built-in function sort
The list is sorted by the absolute value of each of these values
L1 = [1,3,5,-2,-4,-6= sorted (l1,key=ABS)print(L1)print(L2)
the list is sorted by absolute value
The list is sorted by the len of each element
L = [[1,2],[3,4,5,6], (7,),'123')print(sorted (L,key=len))
Exercises
1. Use map to process the list of strings and turn everyone in the list into SB, for example ALEX_SB
name=[' Alex ', ' Wupeiqi ', ' Yuanhao ', ' Nezha ']
2. Use the filter function to process the list of numbers and filter out all the even number in the list
num = [1,3,5,6,7,8]
3. Feel free to write a file with more than 20 lines
Run the program, read the contents into memory first, and store it in a list.
receive user Input page number, each page 5, output only when the content of the page
4. Below, the name of each dictionary corresponds to the stock name, shares corresponds to how many shares, price corresponds to the stock prices
Portfolio = [
{' name ': ' IBM ', ' shares ': +, ' price ': 91.1},
{' name ': ' AAPL ', ' shares ': +, ' price ': 543.22},
{' name ': ' FB ', ' shares ': $, ' Price ': 21.09},
{' name ': ' HPQ ', ' shares ': +, ' price ': 31.75},
{' name ': ' YHOO ', ' shares ': $, ' Price ': 16.35},
{' name ': ' ACME ', ' shares ': +, ' price ': 115.65}
]
4.1. Calculate the total price of each stock purchased
4.2. Filter out the stock with a unit price greater than 100
Python built-in function