python3 function description

Reprinted from the detailed explanation of Python3 built-in functions


1. Introduction 

 Python has built-in a series of commonly used functions for us to use, the official English documentation of python describes in detail: click to view, for the convenience of viewing, record the summary of the built-in functions.

2. Instructions for use

  The following are all built-in functions for the Python 3 version:

  1. abs() to get the absolute value

abs(-10)
10
abs(10)
10
abs(0)
0
a = -10
a.abs()
10

  1. all() takes an iterator and returns True if all elements of the iterator are true, otherwise returns False

tmp_1 = [‘python’,123]
all(tmp_1)
True
tmp_2 = []
all(tmp_2)
True
tmp_3 = [0]
all(tmp_3)
False

  1. any() accepts an iterator and returns True if an element in the iterator is true, otherwise returns False

  2. ascii() calls the repr () method of the object and gets the return value of the method.

  3. bin(), 6. oct(), 7. hex() The functions of the three functions are: convert the decimal number to 2/8/16 hexadecimal respectively.

  4. bool() tests whether an object is True or False.

  5. bytes() converts a string to bytes

s = ‘python’
x = bytes(s, encoding=’utf-8’)
x
b’python’
a = ‘王’
s = bytes(a, encoding=’utf-8’)
s
b’\xe7\x8e\x8b’

  1. str() converts character type/numeric type, etc. to string type

str(b'\xe7\x8e\x8b', encoding='utf-8') # bytes converted to string
'wang'
str(1) # integer converted to string
'1'

  1. callable() determines whether the object can be called. The object that can be called is a callables object, such as functions and instances with call ().

callable(max)
True
callable([1, 2, 3])
False
callable(None)
False
callable(‘str’)
False

  1. char(), 13. ord() View the ASCII character corresponding to a decimal number / view the decimal number corresponding to an ASCII.

chr(-1)
Traceback (most recent call last):
File “

call method

Province.show()

  1. complie() Compiles strings into code that python can recognize or execute, and can also read text into strings and then compile.

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Compile source into code or AST object. Code objects can be executed via the exec statement or evaluated with eval().
Parameter source: string or AST (abstract syntax trees) object.
Parameter filename: code file name, pass some recognizable value if the code is not read from a file.
Parameter model: Specifies the type of compiled code. 'exec', 'eval', 'single' can be specified.
Parameters flag and dont_inherit: These two parameters are optional parameters.

s = “print(‘helloworld’)”
r = compile(s, “”, “exec”)
r

Output result:

0 a
1 b
2 c

  1. eval() evaluates the string str as a valid expression and returns the result of the evaluation

s = “1+2*3”
type(s)

User input 3

print(num)

output result

3

  1. int() converts a string or numeric value to an ordinary integer

int([x[,radix]])
If the argument is a string, then it may contain a sign and a decimal point. The parameter radix indicates the radix of the conversion (the default is decimal).
It can be a value in the range [2,36], or 0. If it is 0, the system will parse according to the string content.
If the parameter radix is ​​provided, but the parameter x is not a string, a TypeError exception will be thrown;
otherwise, the parameter x must be a numeric value (plain integer, long integer, floating point number). Converts floating point numbers by rounding off the decimal point.
A long integer is returned if it is outside the representation range of an ordinary integer.
If no arguments are provided, the function returns 0.

  1. isinstance() checks if an object is an object of a class, returns True or False

isinstance(obj, cls)
checks if obj is an object of class cls, returns True or False
class Foo(object):
pass
obj = Foo()
isinstance(obj, Foo)

  1. issubclass() checks if a class is a subclass of another class. Return True or False

issubclass(sub, super)
checks if the sub class is a derived class (subclass) of the super class. Return True or False

class Foo(object):
pass

class Bar(Foo):
pass

issubclass(Bar, Foo) 

  1. iter () 

iter(o[, sentinel])
returns an iterator object. The function's resolution of the first argument depends on the second argument.
If the second parameter is not provided, the parameter o must be a collection object that supports the traversal function ( iter () method) or the sequence function ( getitem () method), and the
parameter is an integer, starting from zero. If neither of these features is supported, a TypeError exception will be penalized.
If the second parameter is provided, the parameter o must be a callable object. In this case, an iterator object is created, and each time the iterator's next() method is called to call o without
parameters , if the return value is equal to the parameter sentinel, a StopIteration exception will be triggered, otherwise the value will be returned.

  1. len() returns the object length, the parameter can be a sequence type (string, tuple or list) or a map type (such as a dictionary)

  2. list() List constructor.

list([iterable])
Constructor for list. The parameter iterable is optional, it can be a sequence, a container object that supports compilation, or an iterator object.
This function creates a list of element values ​​in the same order as the parameter iterable. If the parameter iterable is a list, a copy of the
list  and returned, as in the statement iterables[:].

  1. locals() prints a dictionary of currently available local variables

Do not modify the contents of the dictionary returned by locals(); changes may not affect the parser's use of local variables.
Calling locals() in the function body returns free variables. Modifying a free variable does not affect the parser's use of the variable.
Free variables cannot be returned within a class area.

  1. map()

map(function, iterable,...)
applies the fuction function to each element in the argument iterable and returns the result as a list.
If there are multiple iterable parameters, then the fuction function must receive multiple parameters, and the elements at the same index in these iterables will be used as parameters of the function function in parallel.
If the number of elements in one iterable is less than the other, then None will be used to extend the iterable to make the number of elements the same.
If there are multiple iterables and function is None, map() will return a list of tuples, each tuple containing the value at the corresponding index in all iterables.
The parameter iterable must be a sequence or any traversable object, and the function returns a list (list).

li = [1,2,3]
data = map(lambda x :x*100,li)
print(type(data))
data = list(data)
print(data)

operation result:

output

1024

  1. print() output function

The print statement in python2 was replaced by the print() function in python3.
How to limit the default newline of print:
1. Under the python2 version, add a comma ',' at the end of the print output
2. After python3.4, print(value, …,sep=”,end='\n',file= sys.stdout, flush=False), just set end to empty.

  1. property()

  2. range() generates a specified range of numbers as needed, giving you the control you need to iterate a specified number of times

Used to create a list (list) containing consecutive arithmetic values. Often used in for loops. Arguments must be plain integers.
The default value of the parameter step is 1, and the default value of the parameter start is 0.
Calling this function with full arguments will return a list of plain integers.
step can be a positive or negative integer. It cannot be 0, otherwise a ValueError will be penalized.
range(3) represents 0,1,2. Equivalent to range(0,3)

range(0,10,2) #The first parameter is the starting number, the second is the ending number (excluding this), and the third number is the number of steps
[0,2,4,6,8]

  1. repr() converts an arbitrary value to a string for the timer to read

repr(object)
returns a string representation of an object. Sometimes this function can be used to access operations.
For many types, repr() attempts to return a string that the eval() method can use to produce the object;
otherwise, enclosed in angle brackets, a string containing the class name and other secondary information is returned.

  1. reversed() reverse, reverse order object

reversed(seq)
returns an iterator object in reverse order. The parameter seq must be an object containing a reversed () method or support sequence operations ( len () and getitem ())
This function is new in 2.4

  1. round() rounds

round(x [, n])
rounds the n+1th decimal place of the argument x, returning a floating-point number with n decimal places.
The default value of parameter n is 0. The result is a float. For example, round(0.5) results in 1.0

round(4,6)
4
round(5,6)
5

  1. set() class set([iterable]) returns a new set object that can select elements from iterable, set is a built-in class.

  2. setattr() corresponds to getattr(), the parameters of setattr(object,name,value) are an object, a string and an arbitrary value. Strings can name existing properties or new properties. If the object allows it, the function will assign to the property.

setattr(x, 'foobar', 123) is equivalent to x.foobar = 123

  1. slice() slice function, slice(start, stop[, step])

  2. sorted() sort

sorted([36,6,-12,9,-22]) list sorted
[-22, -12, 6, 9, 36]
sorted([36,6,-12,9,-22],key=abs ) higher-order function, sorted by absolute value size
[6, 9, -12, -22, 36]
sorted(['bob', 'about', 'Zoo', 'Credit']) String sorting, according to ASCII Size sorting
['Credit', 'Zoo', 'about', 'bob']
If you need to sort a tuple, you need to use the parameter key, which is the keyword.
a = [('b',2), ('a',1), ('c',0)]
list(sorted(a,key=lambda x:x[1])) by tuple second Elements sorted
[('c', 0), ('a', 1), ('b', 2)]
list(sorted(a,key=lambda x:x[0])) by tuple first Element Sort
[('a', 1), ('b', 2), ('c', 0)]
sorted(['bob', 'about', 'Zoo', 'Credit'],key=str .lower) ignore case sorting
['about', 'bob', 'Credit', 'Zoo']
sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower, reverse=True) reverse sort
['Zoo', 'Credit', 'bob', 'about']

  1. staticmethod() A function that defines a static method in a class, usually @staticmethod is followed by a function, so use

  2. str() String constructor

  3. sum() summation

  4. super() calls the method of the parent class

  5. tuple() tuple constructor

  6. type() shows what type the object belongs to

  7. vars() vars([object]) returns the dict attribute of a module, class, instance or any other object using the dict attribute.

  8. zip() pairs objects one by one, which is equivalent to making an iterator that aggregates the elements of each iteration. zip(*iterables)

list_1 = [1,2,3]
list_2 = [‘a’,’b’,’c’]
s = zip(list_1,list_2)
print(list(s))

operation result:

[(1, ‘a’), (2, ‘b’), (3, ‘c’)]

  1. import()

    This function is called by an import statement, and it can be replaced (import builtins module and assigned to builtins.import ) to change the semantics of the import statement, but this is not recommended.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325924533&siteId=291194637