好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

python常用内建函数

1.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]

>>> list(map(lambda x,y:x+y,[1,2,3],[4,5,6])) [5, 7, 9]

 

2.filter函数(对指定序列按照规则执行过滤操作,返回传入的参数)

>>> list(filter(lambda x:x%2,[1,2,3,4])) [1, 3] >>> list(filter(lambda x:x/2,[1,2,3,4])) [2, 3, 4]

>>> filter(None,‘hello‘) ‘hello‘

3.reduce函数(对参数序列中元素进行累积)

>>> reduce(lambda x,y:x+y,[1,2,3,4,5],6) 21 >>> reduce(lambda x,y:x*y,[1,2,3,4,5],6) 720

>>> def f(x,y): ... return x*y ... >>> l=range(1,6) >>> reduce(f,l) 120

4.zip函数(将可迭代对象元素对应下标两两组合打包成包含元组的列表)

>>> a=[1,2,3] >>> b=[4,5,6,7] >>> print(list(zip(a,b))) [(1, 4), (2, 5), (3, 6)]

5.setattr()、getattr()函数(分别为设置和获取对象的属性,对象的方法也是对象的属性)

>>> class A(object): ... name="milo" ... def click(self): ... print(123) ... >>> a=A() >>> x=getattr(a,"name") >>> print x milo >>> y=getattr(a,"click") >>> print y <bound method A.click of <__main__.A object at 0x0000000003863358>> >>> setattr(a,"age",18) >>> m=getattr(a,"age") >>> print(m) 18

6.callable(object)(如果参数可调用,返回true,否则返回false,类若有一个__call__()方法,实例可被调用)

>>> a=1 >>> callable(a) False

>>> def func(): ... pass ... >>> callable(func) True >>> class A: ... def __call__(self,*args,**kwards): ... pass ... >>> a=A() >>> callable(a) s): True

7.divmod(a,b)(返回商和余数组成的一对数字)

>>> divmod(5,2) (2, 1)

8.isinstance(obj,classinfo)(如果参数是classinfo的实例,返回true,否则返回false)

>>> isinstance("abc",(int,str)) True >>> isinstance(max,(int,str)) False 9.pow(x,y[,z])(返回x的y次方再除以z的余数)

>>> pow(3,2) 9 >>> pow(3,2,4) 1

10.字符串函数

(1)str.capitalize()(第一个字符串大写)

>>> st="i am a student" >>> st.capitalize() ‘I am a student‘

(2)str.replace(obj1,obj2,num=str.count(obj1))(替换obj1为obj2)

>>> t=‘tast‘ >>> t.replace(‘a‘,‘e‘) ‘test‘ >>> t=‘taast‘ >>> t.replace(‘a‘,‘o‘,1) ‘toast‘

(3)str.split(obj,num)(以obj为分隔符切片str,指定分割num个obj)

>>> t=‘abcde‘ >>> t.split(‘c‘) [‘ab‘, ‘de‘] >>> t=‘abcdbcbce‘ >>> t.split(‘c‘,2) [‘ab‘, ‘db‘, ‘bce‘]

(4)str.find(obj,beg=0,end=len(str))(如果obj在字符串中,返回索引值,不在,返回-1)

>>> st ‘i am a student‘ >>> st.find(‘student‘) 7 >>> st.index(‘am‘) 2 >>> st.find(‘studentsa‘) -1

查看更多关于python常用内建函数的详细内容...

  阅读:22次