This article describes the usage of common built-in methods and parameters in Python 3.5. Share it for your reference, as follows:
The detailed explanation of Python's built-in method parameters is as follows:/3/library/?highlight=built#ascii
1、abs(x): Returns a numberAbsolute value. The parameters can beInteger or floating point number. If the parameter is a complex number, its size is returned.
#Built-in function abs()print(abs(-2)) print(abs(4.5)) print(abs(0.1+7j))
Running results:
2
4.5
7.000714249274855
2、all(Iterable):ifAll elements of the iterable object are true (i.e. non-zero) or the iterable object is empty, return True, otherwise return False
#Built-in function all()print(all([-1,0,7.5])) print(all([9,-1.6,12])) print(all([]))
Running results:
False
True
True
3、any(Iterable):ifOne of the elements of the iterable object is true (ie: non-zero), returns True, iterable objectAll elements are zero (all false) or the iterable object is emptyReturns False.
#Built-in function any()print(any([-1,0,7.5])) print(any([0,0,0])) print(any([]))
Running results:
True
False
False
4、ascii(object):WillMemory objects become printable stringsform.
#Built-in function ascii(object)a = ascii([1,2,'Hello']) print(type(a),[a])
Running results:
<class 'str'> ["[1, 2, '\\u4f60\\u597d']"]
5、bin(x):WillConvert decimal integers to binary
#Built-in function bin()print(bin(0)) print(bin(2)) print(bin(8)) print(bin(255))
Running results:
0b0
0b10
0b1000
0b11111111
6. bool([x]): Returns a bool value, 0: Returns False, non-0: Returns True; empty list: Returns False
#Built-in function bool()print(bool(0)) print(bool(1)) print(bool([])) print(bool([3]))
Running results:
False
True
False
True
7. bytearray(): Returns a new byte array, a binary byte format that can be modified.
#built-in function bytearray()a = bytes("abcde",encoding='utf-8') print(a) b = bytearray("abcde",encoding='utf-8') print(b) b[1] = 100 print(b)
Running results:
b'abcde'
bytearray(b'abcde')
bytearray(b'adcde')
8. Callable(object): determines whether it is callable (functions and classes can be called), lists, etc. cannot be called
#built-in function callabledef nice(): pass print(callable(nice)) print(callable([]))
Running results:
True
False
9. chr(i): Returns the ASCII code corresponding to the number; on the contrary, ord(): Returns the ASCII code corresponding to the number
#Built-in functions chr() and ord()print(chr(98)) print(ord('c'))
Running results:
b
99
10. compile(): compile strings into executable code
#built-in function compilecode = "for i in range(10):print(i)" print(compile(code,'','exec')) exec(code)
Running results:
<code object <module> at 0x008BF700, file "", line 1>
0
1
2
3
4
5
6
7
8
9
11. dir(): You can check the method
#built-in function dirs = [] print(dir(s))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__','__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
12. divmod(a,b): Returns the quotient and remainder
#Built-in function divmod()print(divmod(5,3)) print(divmod(8,9))
Running results:
(1, 2)
(0, 8)
13. enumerate(): means enumeration and list.
For an iterable/traversable object (such as lists, strings), enumerate will form an index sequence.
Using it, you can get both index and value; enumerate is mostly used to get counts in for loops.
#Built-in function enumeratelist = ['joyous','welcome','you'] for index,item in enumerate(list): print(index,item)
Running results:
0 Happy
1 Welcome
2 You
13. eval(): evaluate the string str as a valid expression and return the calculation result.
#Built-in function eval()#Convert strings into listsa = "[[1,2], [3,4], [5,6], [7,8], [9,0]]" print(type(a)) b = eval(a) print(b) print(type(b)) #Convert strings to dictionarya = "{1: 'a', 2: 'b'}" print(type(a)) b = eval(a) print(b) print(type(b)) #Convert strings into tuplesa = "([1,2], [3,4], [5,6], [7,8], (9,0))" print(type(a)) b = eval(a) print(b) print(type(b))
Running results:
<class 'str'>
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
<class 'list'>
<class 'str'>
{1: 'a', 2: 'b'}
<class 'dict'>
<class 'str'>
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
<class 'tuple'>
14. filter(function,iterable): filter sequence.
The anonymous function is released after running out and will not be reused.
#Anonymous Functioncalc = lambda n:print(n) calc(3) res = filter(lambda n:n>5,range(10)) for i in res: print(i)
Running results:
3
6
7
8
9
15. map(): You can convert one list to another list, and you only need to pass in the conversion function.
res = map(lambda n:n*n,range(5)) #Equivalent to list generation formula [lambda i:i*i for i in range(5)]for i in res: print(i)
Running results:
0
1
4
9
16
16. reduce(): After python 3.0.0.0, reduce is no longer in the built-in function. If you want to use it, you have tofrom functools import reduce
.
It can operate on the data set in sequence by passing it to a function in the reduce (must be a binary function).
Any problem that needs to operate on a set and that has a statistical result and can be solved by loop or recursive can generally be implemented in reduce.
from functools import reduce res = reduce(lambda x,y:x+y,range(10)) #Sumres1 = reduce(lambda x,y:x*y,range(1,10)) #factorialprint(res) print(res1)
Running results:
45
362880
17. globals(): Returns a dictionary of global variables. If you modify the contents of it, the value will really change.
locals(): will return all local variables at the current position as dict type.
def test(): loc_var = 234 print(locals()) test()
Running results:
{'loc_var': 234}
18. hash(): The function returns the hash value of the object. The returned hash value is represented by an integer, usually used in a dictionary to enable quick query of key values.
print(hash('liu')) print(hash("liu")) print(hash('al')) print(hash(3))
Running results:
-1221260751
-1221260751
993930640
3
19. hex(x): convert a number into hexadecimal
oct(x): convert a number into octal
print(hex(15)) print(hex(32))
Running results:
0xf
0x20
print(oct(8)) print(oct(16)) print(oct(31))
Running results:
0o10
0o20
0o37
20. round(): Returns the rounded value of the floating point number x
print(round(1.3457,3))
Running results:
1.346
21. sorted(): sort
a = {6:2,8:0,1:4,-5:6,99:11,4:22} print(sorted(())) #Sort by keyprint(sorted((),key=lambda x:x[1])) #Sort by key value
Running results:
[(-5, 6), (1, 4), (4, 22), (6, 2), (8, 0), (99, 11)]
[(8, 0), (6, 2), (1, 4), (-5, 6), (99, 11), (4, 22)]
22. Zip(): Accepts any multiple (including 0 and 1) sequences as parameters and returns a tuple list.
a = [1,2,3,4] b = ['a','b','c','d'] for i in zip(a,b): print(i)
Running results:
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
23. __import__('decorator') is equivalent to import decorator
Readers who are interested in Python related content can view the special topic of this site:Summary of Python function usage tips》、《Introduction and Advanced Tutorial on Object-Oriented Programming in Python》、《Python data structure and algorithm tutorial》、《Summary of Python string operation skills》、《Summary of Python encoding operation skills"and"Python introduction and advanced classic tutorials》
I hope this article will be helpful to everyone's Python programming.