码迷,mamicode.com
首页 > 其他好文 > 详细

内置方法map、reduce、filter

时间:2017-05-12 01:46:49      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:test   ati   pytho   ini   一行代码   highlight   cto   代码实现   tool   

map:

     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.

l1 = [1,2,3,4,5,6,7,8,9]
def func(a):
    return a*10

l2 = map(func,l1)
print(l2)   # <map object at 0x0000000000A7CB00>  也是一个迭代器
for i in l2:
    print(i)

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.

from functools import reduce   #内置函数reduce需要导入后才能使用。

l1 = [1,2,3,4,5,6,7,8,9]

def func(a,b):
    return a+b

l2 = reduce(func,l1)
print(l2)

filter:

    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.‘‘‘
# 一行代码实现对列表a中的偶数位置的元素进行加3后求和
a = [1,2,3,4,5]
l = sum([j+3 for j in  list(filter(lambda i:a.index(i)%2 == 0, a))])    #用到了过滤器和匿名函数
print(l)

 

内置方法map、reduce、filter

标签:test   ati   pytho   ini   一行代码   highlight   cto   代码实现   tool   

原文地址:http://www.cnblogs.com/yangxiaoling/p/6843395.html

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