Python中特殊函数和表达式 filter,map,reduce,lambda

1. filter

官方解释:filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.

传入参数:function或None,序列

功能:将按照function中定义的方式进行过滤,返回True的留下,返回False的剔除。

1 #coding=utf-8
2 def findPositiveNum(num):
3     if num > 0:
4         return True
5     else:
6         return False
7     
8 list={2,1,3,-2,0,12,5,-9}
9 print filter(findPositiveNum,list)
View Code

返回结果:

[1, 2, 3, 5, 12]

  

2. map

官方解释:

map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given,  the function is called with an argument list consisting of the  corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return  a list of the items of the sequence (or a list of tuples if more than one sequence).

传入参数:function或None,序列

功能:将序列的中的各个参数传入function中作为参数执行,返回的结果就是序列的值传入function中执行的结果,是一个序列。如果function为None,那么返回值为序列本身。

1 def multiValue(num):
2     return num**2
3 
4 list1={1,3,5,7,9,11}
5 print map(multiValue,list1)
View Code

返回结果:

[1, 9, 25, 49, 81, 121]

如果function传入为None则返回值为

[1, 3, 5, 7, 9, 11]

3. reduce

官方解释:

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,from left to right, so as to reduce the sequence to a single value.For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

将两个参数的函数累积到序列项上,从左到右,以将序列减少到单个的子序列示例中,减少(λx,y:x+y,[1,2,3,4,5])计算(1+2)+3)+4)。如果初始存在,则将其放在计算序列项之前,当序列为空时作为默认值。

1 def addNum(num1,num2):
2     return num1+num2
3 
4 list2={1,2,3,4,5,6}
5 print reduce(addNum, list2)

代码解释:先计算1+2的值,然后将计算的值作为第一个参数传入addNum中,第二个参数为3,依次类推。 最终结果为:

21

如果传入初始值得话则:

1 def addNum(num1,num2):
2     return num1+num2
3 
4 list2={1,2,3,4,5,6}
5 #print reduce(addNum, list2)
6 print reduce(addNum, list2,100)

结果为:

121

4. lambda  可以用来定义匿名函数

1 addnum= lambda x,y:x+y
2 print addnum(1,2)
3 multiNum=lambda x:x**2
4 print multiNum(5)

结果为

3
25

猜你喜欢

转载自www.cnblogs.com/catxjd/p/8970915.html