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

Python interview - reduce & map & filter

时间:2014-11-15 10:11:19      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:python

Python有很多有用有趣的内置函数,比如reduce,map,filter,lambda,zip等。已经写过了lambda和zip相关的博客。继续写关于reduce,map,filter。



Map

首先用help方法看一下map的具体用法。

help(map)

# result

Help on built-in function map in module __builtin__:

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).

map函数,map(function, sequences),然后返回一个list。如果超过一个sequence,那么就会根据function来访问每个list中的依次对应的元素,如果sequence不等长,那么会用None来代替不够的元素。如果function是None,就会返回一个list,或者如果是多个list的话,就会返回一个包含很多tuples的list。


l1 = [1,2,3,4,5]

def func(x):
    return x*x

print map(func, l1)

# result

[1, 4, 9, 16, 25]

如果是两个sequences 

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

def func(x,y):
    return x+y

print map(func, l1, l2)

# result

[7, 9, 11, 13, 15]

方法有所改变,因为是两个lists,所以方法有两个参数。

对于不等长的sequences

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

def func(x,y):
    return y

print map(func, l1, l2)

# result

[6, 7, 8, 9, 10, None]

我们可以看到,较短的list,输出的时候会用None代替。

map可以和lambda一起用

l1 = [1,2,3,4,5]

print map((lambda x: x **2), l1)

# result

[1, 4, 9, 16, 25]

当我们使用lambda作为一个function的时候,我们可以传入list of function作为sequence

def square(x):
        return (x**2)
def cube(x):
        return (x**3)

funcs = [square, cube]
for r in range(5):
    value = map(lambda x: x(r), funcs)
    print value
    
# result

[0, 0]
[1, 1]
[4, 8]
[9, 27]
[16, 64]


如果function是None的话

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

print map(None, l1, l2)

# result

[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]


map就像是一个for loop,对sequence中的元素依次进行操作。

from math import sqrt

def mymap(aFunc, aSeq):
	result = []
	for x in aSeq: result.append(aFunc(x))
	return result

print list(map(sqrt, [1, 2, 3]))

print mymap(sqrt, [1, 2, 3])

# result

[1.0, 1.4142135623730951, 1.7320508075688772]
[1.0, 1.4142135623730951, 1.7320508075688772]




Filter

用help看一下filter的用法

help(filter)

# result

Help on built-in function filter in module __builtin__:

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.

filter函数,同样是filter(function,sequence),返回list,tuple,或者string。返回经过function判断过之后是true的元素。如果function是None,那么就返回true的元素。如果sequence是tuple或者string,返回同样的类型,如果是其他类型,就返回list。

print list(range(-5,5))

print list(filter((lambda x: x<0), range(-5,5)))

# result

[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
[-5, -4, -3, -2, -1]

如果function是None

print list(filter(None, range(-5,5)))

# result

[-5, -4, -3, -2, -1, 1, 2, 3, 4]

只有0没有输出,因为0这里被认为是False。

其他类型

def f(x):
    return x != 'a'

print filter(f, 'abcdef')

# result

bcdef



Reduce

用help看一下reduce的用法

help(reduce)

# result

Help on built-in function reduce in module __builtin__:

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.


reduce函数,reduce(function,sequence[,initial])返回一个值。把sequence中的元素从左往右两个两个根据function操作起来,最终剩下一个值。比如reduce(lambda x,y:x+y,[1,2,3,4,5]) 运行的过程就是((((1+2)+3)+4)+5). initial可以设置作为一个default,如果sequence是空的话。


def add(x,y):
    return x+y


print reduce(add, range(1,11))
print reduce(add, range(1,11), 20)
print reduce(add, [],20)


# result


55 (1+2+3+4+5+6+7+8+9+10)
75 (20+1+2+3+4+5+6+7+8+9+10)
20 (default)<span style="font-family: Arial, Helvetica, sans-serif;"></span>

同样的也可以配合lambda一起使用

print reduce((lambda x, y: x * y), [1, 2, 3, 4])

# result

24 (1*2*3*4)


Python interview - reduce & map & filter

标签:python

原文地址:http://blog.csdn.net/bearkino/article/details/41141495

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