python filter/map/reduce的用法

来源:互联网 发布:黑蜂无人机淘宝 编辑:程序博客网 时间:2024/04/29 21:57
filter(...)  #filter函数中的函数的返回类型是bool型的
    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.

def func(x):
    if x > 't':
        return x
    

filter(lambda x: x>=0,datalist)
filter(lambda x:x >='t','strxxx')
filter(None,'strxxx')
filter(func,'strxxx')
filter(lambda x : x >4,tuple1)


help(map)
Help on built-in function map in module __builtin__:

map(...) map用来快速生成一个列表,函数中的function 是个表达式,对后面给定的列表进行一定的运算,如果碰到后面有几组列表传进来,map会试着去将这个几个seq 组合起来
    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).
    
map(lambda x,y,z: str(x) + str(y) +str(z),('xxx','yyyzzz'),('123','456'),('abc','def'))
==>['xxx123abc', 'yyyzzz456def']
==>str1 = map(lambda h: h.replace(' ',''),str1)
str1 =["aa","bb","c c","d d","e e"]
str1 = map(lambda h: h.replace(' ',''),str1)
print str1
['aa', 'bb', 'cc', 'dd', 'ee']


>>> help(reduce)
Help on built-in function reduce in module __builtin__:

reduce(...) #reduce从sequence中取出两个元素,把这个两个元素作为结果1,再取第三个元素,结果1和第三个元素 会得出结果2,如此迭代完列表中所有的元素
    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.

>>>

reduce(lambda a,b: a&b,map(dict.viewkeys,[dict1,dict2,dict3]))  #取出三个字典中的key的交集,注意这里将map也用进来了
print reduce(func,map(dict.viewkeys,[dict1,dict2,dict3]))
print reduce(lambda x,y:x + y,[1,2,3,4,5])   #reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5)
0 0
原创粉丝点击