Python 高阶函数filter、map、reduce、reversed、sorted及迭代器函数 iter
1. filter(function, iterable)
過(guò)濾器,過(guò)濾掉不滿足函數(shù) function 的元素,重新返回一個(gè)新的迭代器。
其中 function 函數(shù)的第一個(gè)參數(shù)是可迭代對(duì)象 iterable 中的一個(gè)元素,也就是說(shuō)函數(shù) function 依次接收 iterable 可迭代對(duì)象的每一個(gè)元素,并判斷每一個(gè)元素是否符合 function 的條件。
In [29]: a = [1,2,3,4,5]In [30]: def fun(a):...: ret = []...: if a > 3:...: ret.append(a)...: return ret...: In [31]: for i in filter(fun, a):...: print(i)...:
4
5In [32]: list(filter(fun, a))
Out[32]: [4, 5]
2. map(function, iterable, …)
它將 function 映射于 iterable 中的每一項(xiàng),并返回一個(gè)新的迭代器。
In [33]: a = [1,2,3,4,5]In [34]: map(lambda x: x*2, a)
Out[34]: <map at 0x843d400>In [35]: ret = map(lambda x: x*2, a)In [37]: list(ret)
Out[37]: [2, 4, 6, 8, 10]
同時(shí)我們, map 函數(shù)支持傳入多個(gè)可迭代對(duì)象。當(dāng)傳入多個(gè)可迭代對(duì)象時(shí),輸出元素個(gè)數(shù)等于較短序列長(zhǎng)度。
如下,傳入兩個(gè)列表, function 就需要接受兩個(gè)參數(shù),取值分別對(duì)應(yīng)第一、第二個(gè)列表中的元素。找到同時(shí)滿足第一個(gè)列表的元素為奇數(shù),第二個(gè)列表對(duì)應(yīng)位置的元素為偶數(shù)的元素。
In [38]: xy = map(lambda x,y: x%2==1 and y%2==0, [1,3,2,4,1],[3,2,1,2])In [39]: for i in xy:...: print(i)...:
False
True
False
False
In [40]: a = [1,2,3,4,5]In [41]: b = [10,11]In [42]: ret = map(lambda i,j: i+j, a, b)In [43]: list(ret)
Out[43]: [11, 13]
3. reduce(function, iterable[, initializer])
reduce 函數(shù)在 Python 3 中位于 functools 模塊中,使用前需要先導(dǎo)入。
reduce 函數(shù)中第一個(gè)參數(shù)是函數(shù) function 。 function 函數(shù),參數(shù)個(gè)數(shù)必須為 2,是可迭代對(duì)象 iterable 內(nèi)的連續(xù)兩項(xiàng)。它的計(jì)算過(guò)程是依次將 iterable 2 個(gè)元素為單位傳遞給 function 。
In [45]: from functools import reduceIn [46]: reduce(lambda x,y: x+y,list(range(5)))
Out[46]: 10
即它的計(jì)算結(jié)果是 0+1+2+3+4=10
4. reversed(seq)
重新生成一個(gè)反向迭代器,對(duì)輸入的序列實(shí)現(xiàn)反轉(zhuǎn)。注意:它會(huì)返回一個(gè)新的迭代序列。
In [47]: a = [1,2,3,4,5]In [48]: ret = reversed(a)In [49]: ret
Out[49]: <list_reverseiterator at 0x8940f60>In [50]: list(ret)
Out[50]: [5, 4, 3, 2, 1]
5. sorted(iterable, *, key=None, reverse=False)
實(shí)現(xiàn)對(duì)可迭代對(duì)象的排序, key 參數(shù)和 reverse 參數(shù)必須為關(guān)鍵字參數(shù),都可省略。
In [51]: a = [3,1,2,5,4]In [52]: ret = sorted(a, reverse=True)In [53]: ret
Out[53]: [5, 4, 3, 2, 1]In [54]: ret = sorted(a, reverse=False)In [55]: ret
Out[55]: [1, 2, 3, 4, 5]
可迭代對(duì)象的元素也是一個(gè)復(fù)合對(duì)象,如為字典。依據(jù)依據(jù)為字典鍵的值, sorted 的 key 函數(shù)就會(huì)被用到。
In [62]: d = [{'a':111, 'b':222, 'c':333}, {'a':11, 'b':22, 'c':33}, {'a':1, 'b':2, 'c':3}]In [63]: sorted(d,key=lambda x:x['a'])
Out[63]:
[{'a': 1, 'b': 2, 'c': 3},{'a': 11, 'b': 22, 'c': 33},{'a': 111, 'b': 222, 'c': 333}]
6. 迭代器函數(shù) iter(object[, sentinel])
返回一個(gè)嚴(yán)格意義上的可迭代對(duì)象,其中,參數(shù) sentinel 可有可無(wú)。
In [64]: a = [1,2,3]In [65]: ret = iter(a)In [66]: ret
Out[66]: <list_iterator at 0x7feba20>In [67]: ret.__next__()
Out[67]: 1In [68]: ret.__next__()
Out[68]: 2In [69]: ret.__next__()
Out[69]: 3In [70]: ret.__next__()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-70-6685d4123b21> in <module>
----> 1 ret.__next__()StopIteration: In [71]: for i in ret:...: print(i)...: In [72]:
可以看到最后 for i in ret 中已經(jīng)沒(méi)有元素可進(jìn)行迭代,所以 print(i) 不會(huì)有值再打印。
只要 iterable 對(duì)象支持可迭代協(xié)議,即自定義了 __iter__ 函數(shù),便都能配合 for 依次迭代輸出其元素。
In [73]: class Iter(object):...: def __init__(self):...: self._list = [1,2,3]...: def __iter__(self):...: print("enter __iter__")...: return iter(self._list)...: In [74]: m = Iter()In [77]: for i in m:...: print(i)...:
enter __iter__
1
2
3In [78]:
如果在 Iter 類(lèi)中不使用 iter(self._list) 則會(huì)有如下錯(cuò)誤:
In [78]: class Iter(object):...: def __init__(self):...: self._list = [1,2,3]...: def __iter__(self):...: print("enter __iter__")...: return self._list...: In [79]: m = Iter()In [80]: for i in m:...: print(i)...:
enter __iter__
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-80-9cd7b7f0b3b5> in <module>
----> 1 for i in m:2 print(i)3 TypeError: iter() returned non-iterator of type 'list'
總結(jié)
以上是生活随笔為你收集整理的Python 高阶函数filter、map、reduce、reversed、sorted及迭代器函数 iter的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 乌镇客运站到西栅多远
- 下一篇: Python 关键字 global、no