Summary of python's Usage of Common Built-in Functions

One of the built-in function python object types can be directly used without importing any additional modules. They are all encapsulated in the built-in module _builtins_ and implemented in C language. They are optimized in a large number and run very fast.

You can use help (function name) to see the use of a function
Because the number of built-in functions is large and powerful, so we first briefly introduce a part, and then slowly contact through the content.

Type Conversion and Type Judgment
  • bin(), oct(), hex()
    Integers can be converted into binary, octal and hexadecimal forms respectively, but the parameters must be integers.
#The output is 0b1000101011
#The output is'0o153'
#The output is'0x22b'
  • int(), float()
    Converting other types of digits to integers allows the second parameter base to explain the process of digit strings when the parameter is a digit string.
int(-3.2) #Output is -3
int('0x22b', 16) #Hexadecimal to decimal
int('22b', 16) Ditto

int(bin(54321), 2) #Conversion of binary and decimal systems
int('0b111') #The second parameter, 0, represents the process implicit in the use of strings
float(3) #Output is 3.0
float('3.5') #Converting a numeric string to a real number
complex(3) #Specifies the real part, which can be used to generate complex numbers

  • ord(), chr()
    Contrary function
    Unicode code code used to return a single character
    chr() is used to return the character corresponding to Unicode code code, and str() converts any type of parameter into a string.
  • list(), tuple(), dict(), set(), frozenset()
    Convert other data types to our lists, tuples, dictionaries, variable sets, immutable sets, or for creating
list(range(5)) #Convert range objects to lists
#The output is [0,1,2,3,4]

tuple(_) #An underscore represents the correct output of the last time.
#The output is (0,1,2,3,4)

dict(zip('1234','abcde')) #Create a dictionary
#The output is {4':'d','2':'b','3':'c','1':'a'}.

set('1112234') #Create variable collections to automatically remove duplication
#The output is {4','2','3','1'}
  • type(), isinstance()
    Judging the data type, which is used to check the parameters of the function, can prevent the wrong parameter type from causing the function to crash or returning unexpected results.
type(3) #View the type of 3, int
type([3]) #list type

isinstance(3, int) #Examples to determine whether 3 is of type int
#Return to True

isinstance(3j, (int, float, complex)) #Determine whether 3 is an int, float, complete type
#Return to True
  • max(), min(), sum()
    Used to calculate the maximum, minimum and sum of all elements in a list, tuple, or other iterative object containing finite elements
from random import randint
a = [randint(1, 100) for i in range(10)]
#A list of 10 random numbers between [1,100]
print(max(a), min(a), sum(a)) #Maximum, minimum, sum of all elements
sum(a)/len(a) #average value
  • input(), print()
    The former is used to receive user's keyboard input, and the latter is used to output data in a specified format to a standard console or a specified file object.
x = input('Please input: ')
#Output: Please input: 345

The actual print() grammar format is

print(value1,value2,...,sep=' ', end = '\n', file=sys.stdout,flush=False)
print(1,3,5,7, sep='\t')
#Modify the default delimiter
#Output is 135 7

for i in range(10): 
	print(i, end =' ') #Modify the end parameter so that no line changes after each output
#Output is 0 1 2 3 4 5 6 7 8 9
  • read(), readline()
    Receive a specified number of characters from the keyboard
import sys
x = #Read 5 characters, if less than 5, wait for input
#If more than five, truncate

x = sys.stdin.readline() #Read 5 characters, if not enough, wait for further input
#When you encounter a newline character, it ends, and more than five are truncated.
  • pprint()
    More friendly output function, better control of output format, output content more than one line will automatically add newlines and indentation to show the structure of the content
import pprint
t = [[[]]]
#The default width is 80
pprint.pprint(t, width=50) 
#Automatically set the width, change lines as needed, indent
  • sorted(), reversed()
x = list(range(11))
import random
random.shuffle(x) #Disruption of order
sorted(x) #Sort in default order
sorted(x, key=str) #Arrange in descending order of length after converting to a string
  • enumerate() function
    Enumeration of elements in an iteratable object, returning an iteratable enumerate object, where each element is a tuple containing an index and a value
list(enumerate('abcd')) #Enumeration of elements in strings
#The output is [(0,'a'), (1,'b', (2,'c'), (3,'d')]

list(enumerate['python', 'Greate'])
#The output is [(0,'python'), (1,'Greate')]
  • map(), reduce(), filter()
    map() maps a function func to each element of a sequence or iterator object in turn, and returns an iterative map object as a result
    reduce() can iteratively accumulate a function that receives two parameters from left to right on all elements of a sequence or iterator object
    filter() acts on a sequence of single-parameter functions, but a filter object consists of those elements in the sequence that make the function return True
list(map(str, range(5))) #Convert the elements in the list to strings

  • range()
    The grammatical format is
    range([start,] end [,step])
    Three forms of range(stop), range(start, stop) range(start, end, step)
    Where [start, end] is left open and right closed, step is an integer of step size
range(5) #start defaults to 0, step defaults to 1
range(1,10,2) #Specify start value and step size
range(9,0,-2) #Step size is negative, start is larger than end
  • zip()
    Squeeze elements from multiple iterative objects and return a zip object

  • eval(), exec()
    eval() is used to calculate the value of a string, or to execute code objects generated by compile() compilation of built-in functions.
    exec() is used to execute the specified python source code or code objects compiled by compile().

eval(b'3+5') #Output 8
eval('9') #Converting digital strings to numbers
eval('09')#Throw an exception. No number starting with 0 is allowed.
exec('x=3') #Execution statement x=3
exec('help(sum)') #View the help documentation for the built-in function sum

Tags: Python less C

Posted on Sat, 07 Sep 2019 01:13:27 -0700 by swallace