Python中的map、reduce和filter淺析

來源:互聯網
上載者:User
1、先看看什麼是 iterable 對象

以內建的max函數為例子,查看其doc:
複製代碼 代碼如下:


>>> print max.__doc__
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.


在max函數的第一種形式中,其第一個參數是一個 iterable 對象,既然這樣,那麼哪些是 iterable 對象呢?
複製代碼 代碼如下:


>>> max('abcx')
>>> 'x'
>>> max('1234')
>>> '4'
>>> max((1,2,3))
>>> 3
>>> max([1,2,4])
>>> 4


我們可以使用yield產生一個iterable 對象(也有其他的方式):
複製代碼 代碼如下:


def my_range(start,end):
''' '''
while start <= end:
yield start
start += 1


執行下面的代碼:
複製代碼 代碼如下:


for num in my_range(1, 4):
print num
print max(my_range(1, 4))


將輸出:
複製代碼 代碼如下:


1
2
3
4
4



2、map

在http://docs.python.org/2/library/functions.html#map中如此介紹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 is 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函數使用自訂的function處理iterable中的每一個元素,將所有的處理結果以list的形式返回。例如:
複製代碼 代碼如下:


def func(x):
''' '''
return x*x

print map(func, [1,2,4,8])
print map(func, my_range(1, 4))


運行結果是:
複製代碼 代碼如下:


[1, 4, 16, 64]
[1, 4, 9, 16]


也可以通過列表推導來實現:
複製代碼 代碼如下:


print [x*x for x in [1,2,4,8]]

3、reduce

在http://docs.python.org/2/library/functions.html#reduce中如下介紹reduce函數:
複製代碼 代碼如下:


reduce(function, iterable[, initializer])
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.


這個已經介紹的很明了,
複製代碼 代碼如下:

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])


相當於計算
複製代碼 代碼如下:


((((1+2)+3)+4)+5)


而:
複製代碼 代碼如下:


reduce(lambda x, y: x+y, [1, 2, 3, 4, 5],6)


相當於計算
複製代碼 代碼如下:


(((((6+1)+2)+3)+4)+5)


4、filter

在http://docs.python.org/2/library/functions.html#filter中如下介紹filter函數:
複製代碼 代碼如下:


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


參數function(是函數)用於處理iterable中的每個元素,如果function處理某元素時候返回true,那麼該元素將作為list的成員而返回。比如,過濾掉字串中的字元a:
複製代碼 代碼如下:


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

print filter(func, 'awake')


運行結果是:
複製代碼 代碼如下:


wke


這也可以通過列表推導來實現:
複製代碼 代碼如下:


print ''.join([x for x in 'awake' if x != 'a'])
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.