码迷,mamicode.com
首页 > 编程语言 > 详细

Python函数式编程 map reduce filter

时间:2017-05-01 12:56:30      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:hid   for   代码   函数   tool   arguments   class   erro   编程   

 

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

 

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

标签:hid   for   代码   函数   tool   arguments   class   erro   编程   

原文地址:http://www.cnblogs.com/ttrrpp/p/6791476.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!