您的位置:首页 > 编程语言 > Python开发

python map(),zip(),filter()函数解析

2015-12-08 10:22 681 查看
首先看map函数的定义

map(function, iterable, ...)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and applied to the items from all iterables in parallel. If one iterable is shorter than another
it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation).
The iterable arguments may be a sequence or any iterable object; the result is always a list.

简单来说,map将iterable的每一个元素作用到function中,并且将结果以一个列表的形式返回。

在这里举一个简单的例子,计算从1到100的平方。

我们可以这样做,首先定义一个计算平方值的函数。

def square(a):
print a * a
然后使用map函数

map(square, range(100))
就可以得到从0到99的平方值了。

zip([iterable,...])

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequence or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments
which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

zip() in conjunction with the * operator can be used to unzip a list.

这个函数返回一个元组,其中第i个元组包含来自于参数序列或者可迭代对象的第i个元素。

x=[1,2,3]
y=[4,5,6]
zippped = zip(x,y)
其中zipped的结果为

[(1, 4), (2, 5), (3, 6)]


filter(function, iterable)

Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. It iterable is a string or a tuple, the result also has that type; otherwise it is
always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>>
>>> print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: