# python中内置函数 用来计算字符串的值_python常用内置函数使用

max() 求最大值(列表、元组、序列)

min() 求最小值

len() 求长度

>>> a = [1,2,3,4]

>>> max(a)

4

>>> min(a)

1

>>> len(a)

4

>>>

divmod() 求运算模，返回一个元组，第一个参数是商，第二个是余数

pow(x,y) 指数运算，x的y次方

pow(x,y,z) x的y次方，在与z取模

round() 浮点数>>> a = 3

>>> b = 4

>>> divmod(a,b)

(0, 3)

>>> divmod(b,a)

(1, 1)

>>> pow(a,b)

81

>>> pow(a,b,8)

1

>>>

>>> a/b

0.75

>>> round(a/b)

1

>>> round(a/b,2)

0.75

>>> round(a/b,4)

0.75

>>>

isinstance(l,list) 测试l是否是一个list

>>> def f(x):

pass

>>> callable(fc)

Traceback (most recent call last):

File "", line 1, in

callable(fc)

NameError: name 'fc' is not defined

>>> callable(f)

True

>>>

>>> l = [1,2,3,4]

>>> t = (2,3,4,5)

>>> s = 'hello'

>>> isinstance(l,list)

True

>>> isinstance(t,tuple)

True

>>> isinstance(s,str)

True

>>> isinstance(l,str)

False

str.capitalize() 首字母大写

str.replace(‘x’,’y’,count) 字符串替换 count 替换几次

str.split(“”，sep) 将字符串转换为列表，用“”切割，sep切割几次

>>> str1 = 'hello world , today is very good day'

>>> str1.capitalize()

'Hello world , today is very good day'

>>> str1

'hello world , today is very good day'

>>> str1.replace('o','9',1)

'hell9 world , today is very good day'

>>> str1.replace('o','9',3)

'hell9 w9rld , t9day is very good day'

>>> str1.replace('o','9')

'hell9 w9rld , t9day is very g99d day'

>>>

>>> ip = '192.168.1.254'

>>> ip.split(".")

['192', '168', '1', '254']

>>> ip.split(".",1)

['192', '168.1.254']

>>>

filter() 过滤函数

filter(f,l) 将l列表中的值传给函数f进行判断，保留满足要求的数值 函数return True

zip() 将两个列表的值进行对应，以元组存放在列表中。以最短的为组合数

map(None,a,b) 将列表a、b的值对应起来传给None函数，None可以作为函数

fc(x,y)

reduce(fc,list) 将列表list的值依次传输给函数fc

>>> def f(x):

if x>5:

return True

>>> l = [1,2,3,5,6,2,3,6,7,8]

>>> filter(f,l)

>>> list(filter(f,l))

[6, 6, 7, 8]

>>>

>>> name = ['zhang','li','wang','zhou']

>>> age = [22,21,23,24]

>>> list(zip(name,age))

[('zhang', 22), ('li', 21), ('wang', 23), ('zhou', 24)]

>>> city = ['beijing','shanxi','xinjiang']

>>> list(zip(name,age,city))

[('zhang', 22, 'beijing'), ('li', 21, 'shanxi'), ('wang', 23, 'xinjiang')]

>>>

>>> def f(name,age):

return name,age

>>> list(map(f,name,age))

[('zhang', 22), ('li', 21), ('wang', 23), ('zhou', 24)]

>>>

>>> def f(x,y):

return x+y

>>> a = [1,2,3,4]

>>> b = [1,2,3,4]

>>> list(map(f,a,b))

[2, 4, 6, 8]

>>>

>>>

>>> l = range(100)

>>> reduce(f,l)

Traceback (most recent call last):

File "", line 1, in

reduce(f,l)

NameError: name 'reduce' is not defined

>>>

>>> from functools import reduce

>>> reduce(f,l)

4950

>>> l = range(101)

>>> reduce(f,l)

5050

>>>

>>>

reduce用来计算阶乘很方便。根据reduce，可以写成一行代码来。>>> n = 101

>>> range(n)

range(0, 101)

>>> reduce(lambda x,y:x+y , l)

5050

>>>

+修改为*，就是求n的阶乘了。不对n-1的阶乘。

https://www.cnblogs.com/Renqy/p/12784667.html

08-24

04-19 1357
07-22 4960
05-22 3090
12-08 7924
01-21 4597
10-12 2万+
04-15 4404
06-30 2万+
07-14 1万+
08-06 18万+
08-26 3388
08-02 1008
04-12 1万+