Expression oriented functions of Python provides are:
- map(aFunction, aSequence)
- filter(aFunction, aSequence)
- reduce(aFunction, aSequence)
- lambda
- list comprehension
filter函数的功能相当于过滤器。调用一个布尔函数bool_func来迭代遍历每个seq中的元素;返回一个使bool_seq返回值为true的元素的序列。
filter函数python代码实现:
- def filter(bool_func,seq):
-
filtered_seq = []
-
for eachItem in seq:
-
if bool_func(eachItem):
-
filtered_seq.append(eachItem)
-
return filtered_seq
- >>> a=[2,3,1,5]
-
>>> def isOne(number=1):
-
... if number > 1:
-
... return True
-
...
-
>>> filter(isOne, a)
-
[2, 3, 5]
-
>>>
如果filter参数值为None,list参数中所有为假的元素都将被删除。如下所示:
- >>>a=[0,1,2,3,4,5,6,7]
-
b=filter(None, a)
-
>>>print b
-
>>>[1,2,3,4,5,6,7]
map函数func作用于给定序列的每个元素,并用一个列表来提供返回值。
map函数python实现代码:
- def map(func,seq):
-
mapped_seq = []
-
for eachItem in seq:
-
mapped_seq.append(func(eachItem))
-
return mapped_seq
>>>a=[1,2,3,4,5,6,7]
>>>map(lambda x:x+3, a)
>>>[3,4,5,6,7,8,9,10]reduce函数,func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值。
reduct函数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
- >>> li = [1,2,3,4,5]
-
>>> def reduce_func(li, lis):
-
... return li + lis
-
...
-
>>> reduce(reduce_func, li)
-
15
-
>>>
阅读(1023) | 评论(0) | 转发(0) |