日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Python 高阶函数filter、map、reduce、reversed、sorted及迭代器函数 iter

發(fā)布時間:2023/11/27 生活经验 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 高阶函数filter、map、reduce、reversed、sorted及迭代器函数 iter 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1. filter(function, iterable)

過濾器,過濾掉不滿足函數(shù) function 的元素,重新返回一個新的迭代器。

其中 function 函數(shù)的第一個參數(shù)是可迭代對象 iterable 中的一個元素,也就是說函數(shù) function 依次接收 iterable 可迭代對象的每一個元素,并判斷每一個元素是否符合 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 中的每一項,并返回一個新的迭代器。

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]

同時我們, map 函數(shù)支持傳入多個可迭代對象。當傳入多個可迭代對象時,輸出元素個數(shù)等于較短序列長度。

如下,傳入兩個列表, function 就需要接受兩個參數(shù),取值分別對應第一、第二個列表中的元素。找到同時滿足第一個列表的元素為奇數(shù),第二個列表對應位置的元素為偶數(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 模塊中,使用前需要先導入。

reduce 函數(shù)中第一個參數(shù)是函數(shù) functionfunction 函數(shù),參數(shù)個數(shù)必須為 2,是可迭代對象 iterable 內(nèi)的連續(xù)兩項。它的計算過程是依次將 iterable 2 個元素為單位傳遞給 function

In [45]: from functools import reduceIn [46]: reduce(lambda x,y: x+y,list(range(5)))
Out[46]: 10

即它的計算結(jié)果是 0+1+2+3+4=10

4. reversed(seq)

重新生成一個反向迭代器,對輸入的序列實現(xiàn)反轉(zhuǎn)。注意:它會返回一個新的迭代序列。

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)

實現(xiàn)對可迭代對象的排序, key 參數(shù)和 reverse 參數(shù)必須為關鍵字參數(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]

可迭代對象的元素也是一個復合對象,如為字典。依據(jù)依據(jù)為字典鍵的值, sortedkey 函數(shù)就會被用到。

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

返回一個嚴格意義上的可迭代對象,其中,參數(shù) sentinel 可有可無。

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)沒有元素可進行迭代,所以 print(i) 不會有值再打印。

只要 iterable 對象支持可迭代協(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 類中不使用 iter(self._list) 則會有如下錯誤:

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的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。