Python is often summarized with built in functions

  • 2020-04-02 14:32:45
  • OfStack

1. Mathematics

1. Absolute value: abs(-1)
2. Max ([1,2,3]), min([1,2,3])
3. Sequence length: len(' ABC '), len([1,2,3]), len((1,2,3))
4. Divmod (5,2)//(2,1)
5. Power: pow(2,3,4)//2**3/4
Round (1)//1.0

Ii. Functional correlation

1. Whether the function is callable: callable(funcname). Note that the funcname variable is defined
2. Type judgment: isinstance(x,list/int)
3. Comparison: CMP ('hello','hello')
4. Fast sequence generation :(x)range([start,] stop[, step])

Iii. Type conversion

1, int (x)
2, long (x)
3, float (x)
4. Complex (x) // complex Numbers
5, STR (x)
6, the list (x)
7. Tuple (x) // tuple
8, hex (x)
, oct 9 (x)
CHR (x)// returns the character corresponding to x, for example, CHR (65) returns' A'
11. Ord (x)// returns the ASC code number corresponding to the character, such as ord('A') returns 65

Four, string processing

1. Capitalize: STR. Capitalize


>>> 'hello'.capitalize()

'Hello,'
2. Str.replace

>>> 'hello'.replace('l','2')
'he22o'

Three parameters can be passed, and the third parameter is the number of substitutions

3. String cutting: STR. Split


>>> 'hello'.split('l')
['he', '', 'o']

Two parameters can be passed, the second parameter is the number of cuts

All three of the above methods can be introduced into the String module and called as string.xxx.

Five, the sequence processing function

1. Len: sequence length
2. Max: maximum value in the sequence
3. Min: minimum value
4. Filter: filter sequence


>>> filter(lambda x:x%2==0, [1,2,3,4,5,6])
[2, 4, 6]

5, zip: and row through


>>> name=['jim','tom','lili']
>>> age=[20,30,40]
>>> tel=['133','156','189']
>>> zip(name,age,tel)
[('jim', 20, '133'), ('tom', 30, '156'), ('lili', 40, '189')]

Note that if the sequence length is different, the result will be as follows:

>>> name=['jim','tom','lili']
>>> age=[20,30,40]
>>> tel=['133','170']
>>> zip(name,age,tel)
[('jim', 20, '133'), ('tom', 30, '170')]

6, map: and line traversal, can accept a function type of parameter

>>> a=[1,3,5]
>>> b=[2,4,6]
>>> map(None,a,b)
[(1, 2), (3, 4), (5, 6)]
>>> map(lambda x,y:x*y,a,b)
[2, 12, 30]

7. Reduce

>>> l=range(1,101)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
>>> reduce(lambda x,y:x+y,l)
5050


Related articles: