1、常用函数:abs()、max()、min()、len()、divmod()、pow()、round()
例1:abs返回数字绝对值
abs(10) #结果10 abs(-10) #结果10
例2:max、min取列表最大、最小值
l=[12,34,22,33,45,66] max(l) #结果66 min(l) #结果12
例3:divmod
divmod(5,2) #结果(2,1),其中2是商,1是余数
help(divmod)
其他:
callable():用于测试某个函数是否可以被调用 例如:callable(f)
isinstance():判断某个对象是否属于哪一个类型的 例如:isinstance(l,list) isinstance(l,int)
cmp():用于比较两个字符串 例如:cmp("aab","abcd")
range():生成一个列表 例如:range(10)
xrange():xrange比range的效率要高
2、内置类型转换函数
type()、int()、long()、float()、complex()、str()、list()、tuple()、hex()、oct()、chr()、ord()
3、string函数
capitalize()、replace()、split()
方式一:
str.capitalize():字符串首字母大写
str.replace():替换
例如:
s="hello world" s.replace("hello","good") #返回'good world',原s不变
help(str.replace)
str.split()
方式二:
import String string.replace(s,old,new,times)
4、序列处理函数
len()、max()、min()、filter()、zip()、map()、reduce()
例1:filter()的用法
def f(x): if x>5: return True filter(f,range(10)) #结果[6,7,8,9]
例2:zip()并行遍历举例
name=['a','b','c'] age=[20,30,40] tel=['138','139','151'] zip(name,age,tel) #结果[('a',20,'138'),('b',30,'139'),('c',40,'151')]
例3:map()函数举例
a=[1,3,5] b=[2,4,6] def mf(x,y): return x*y map(None,a,b) #结果[(1,2),(3,4),(5,6)] map(mf,a,b) #结果[2,12,30]
例4:reduce()函数举例
def rf(x,y): return x+y #计算1+2+3+……+100 reduce(rf,range(1,101)) #结果5050
也可以写成:
reduce(lambda x,y:x+y,range(1,101)) #结果5050
例5:综合举例
foo=[3,7,12,22] filter(lambdax:x%3==0,foo) #结果[3,12] #x for x in foo if x%3==0 用列表表达式表示上面的函数
map(lambda x:x*2+10,foo) #结果[16,24,34,54] #x*2+10 for x in foo 用列表表达式表示上面的函数
reduce(lambda x,y:x+y,foo) #结果44