首页 > 代码库 > Python函数式编程 map reduce filter

Python函数式编程 map reduce filter

 

函数式编程,使代码简洁高效。

 

Map函数:

  map(func, *iterables),作用是将一个列表映射到另一个列表。

技术分享
class map(object):
    """
    map(func, *iterables) --> map object
    
    Make an iterator that computes the function using arguments from
    each of the iterables.  Stops when the shortest iterable is exhausted.
    """
View Code

 

使用方法:

def f(x):
    return x**2

li = range(1,10)
res = map(f,li)
print(res)
print(list(res))

"""
<map object at 0x000000000117E2E8>
[1, 4, 9, 16, 25, 36, 49, 64, 81]
"""

       技术分享

 

map(functioniterable...)

map()函数接收两个参数,一个是函数,一个是可迭代的对象,map将传入的函数依次作用到序列的每个元素,返回一个map对象,不是list。

 

基本等价于 [f(x) for x in interable],列表推导比map效率要高一些

map(lambda x: x+1, range(1, 3)) => [x+1 for x in range(1,3)]

 

技术分享
str = ["far","foo","bar"]
mp = map(lambda x:x.upper(),str)
res = list(mp)
print(res)

"""
[‘FAR‘, ‘FOO‘, ‘BAR‘]
"""
View Code

 

 

Reduce函数

  reduce(function, sequence[, initial]),对可迭代对象依次做累计操作,如依次相加或相乘。

  reduce()方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始合并,最终为一个值。

技术分享
def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
    """
    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.
    """
View Code

 

直接使用会报错

reduce(lambda x, y : x + y, [1, 3, 5, 7, 9])
"""
NameError: name ‘reduce‘ is not defined
"""

正确的使用是:reduce是functools中的一个函数,需要引用:from functools import reduce

 

使用方法:

from functools import reduce

res1 = reduce(lambda x, y: x*y, [1, 2, 3])
res2 = reduce(lambda x, y : x + y, [1, 3, 5])
print(res1)
print(res2)

"""
6
9
"""

 

 

Filter函数

  filter(function or None, iterable),作用是按照所定义的函数过滤掉列表中的一些元素

技术分享
class filter(object):
    """
    filter(function or None, iterable) --> filter object
    
    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true.
    """
View Code

 

使用方法:

flt = filter(lambda x: x > 5, range(10))
res = list(flt)
print(flt)
print(res)
"""
<filter object at 0x0000000000649A58>
[6, 7, 8, 9]
"""

 

Python函数式编程 map reduce filter