您的位置:首页 > 编程语言 > Python开发

转 python 的几个内置函数(lambda ,zip, filter, map, reduce )用法

2013-05-28 23:01 1056 查看
1.lambda lambda其实就是一条语句,lambda(x):body。x是lambda函数的参数,参数可以有任意多个(包括可选参数);body是函数体,只能是一个表达式,并且直接返回该表达式的值。
>>>f=lambda x:x+1
>>>f(2)
3
>>>(lambda x,y:x+y)(2,3)
5

2.filter filter(func, list)接受两个参数:一个函数func和一个列表list,返回一个列表。函数func只能有一个参数。filter的功能:列表中所有元素作为参数传递给函数,返回可以另func返回真的元素的列表
>>>l=['abc','acd','1245','ddad','aaa']
>>>func(s)
... return s.startswith('a')
>>>filter(func, l)
['abc','acd','aaa']

filter为过滤list,并返回list,绑定的函数为一个返回bool值的函数
filter(lambda item:item>2,[1,2,3,4])
>>>[3,4]

def fun(x):
return x>2 and x<6
list=[1,2,3,4,5,6,7]
filter(fun,list)
>>> [3,4,5]

3.zip zip函数接受任意多个序列作为参数,将所有序列按相同的索引组合成一个元素是各个序列合并成的tuple的新序列,新的序列的长度以参数中最短的序列为准。另外(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple
>>>x=[1,2,3],y=['a','b','c']
>>>zip(x,y)
[(1,'a'),(2,'b'),(3,'c')]
>>>zip(*zip(x,y))
[(1,2,3),('a','b','c')]

另外一篇内置函数实现的解释

filter内建函数的python实现:

>>> def filter(bool_func,seq):

  >>>filtered_seq = []
  >>>for eachItem in seq:
  >>> if bool_func(eachItem):
  >>> filtered_seq.append(eachItem)
  >>>return filtered_seq

2、

map内建函数的python实现:

>>> def map(func,seq):
>>>mapped_seq = []
>>>for eachItem in seq:
>>> mapped_seq.append(func(eachItem))
>>>return mapped_seq

3、

reduce的python实现:

>>> def reduce(bin_func,seq,initial=None):

>>>lseq = list(seq)
>>>if initial is None:
>>> res = lseq.pop(0)
>>>else:
>>> res = initial
>>>for eachItem in lseq:
>>> res = bin_func(res,eachItem)
>>>return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: