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 >>>
其它小函数
callable() 测试函数是否可被调用
isinstance(l,list) 测试l是否是一个list
>>> def f(x): pass >>> callable(fc) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> 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) <filter object at 0x00000220AC4C95E0> >>> 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 "<pyshell#29>", line 1, in <module> 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用来计算阶乘很方便。根据reduce,可以写成一行代码来。
>>> n = 101 >>> range(n) range(0, 101) >>> reduce(lambda x,y:x+y , l) 5050 >>>
+修改为*,就是求n的阶乘了。不对n-1的阶乘。
小例子动手写一下,印象更深刻。
读书和健身总有一个在路上