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

歡迎訪問 生活随笔!

生活随笔

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

生活经验

Pyhton 内置 itertools 模块chain、accumulate、compress、drop、take等函数使用

發布時間:2023/11/27 生活经验 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Pyhton 内置 itertools 模块chain、accumulate、compress、drop、take等函数使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python 內置的 itertools 模塊使用了 yield 生成器。

1. chain 拼接迭代器

chain 函數實現元素拼接,原型如下,參數 * 表示可變的參數:

chain(*iterables)

使用方法:

In [15]: from itertools import chainIn [16]: a = chain(['This', 'is'], ["python", "qtconsole"])In [17]: type(a)
Out[17]: itertools.chainIn [18]: for i in a:...:     print(i)...:     
This
is
python
qtconsole

2. accumulate 累積迭代器

累積迭代器返回可迭代對象的累積迭代器,函數原型:

accumulate(iterable[, func, *, initial=None])

如果 func 不提供,默認求累積和,使用示例如下:

In [19]: from itertools import accumulateIn [20]: a = accumulate([1,2,3,4])In [21]: for i in a:...:     print(i)...:     
1
3
6
10In [22]: 

如果 func 提供, func 的參數個數要求為 2,根據 func 的累積行為返回結果。

In [22]: a = accumulate([1,2,3,4], lambda x,y: x*y)In [23]: for i in a:...:     print(i)...:     
1
2
6
24In [24]: 

3. compress 漏斗迭代器

compress 函數,功能類似于漏斗功能,所以稱它為漏斗迭代器,原型:

compress(data, selectors)

經過 selectors 過濾后,返回一個更小的迭代器。

In [29]: a = compress("helloworld", [1,0,1,0])In [30]: for i in a:...:     print(i)...:     
h
lIn [31]: 

compress 返回元素個數,等于兩個參數中較短序列的長度。

4. drop 迭代器

掃描可迭代對象 iterable ,從不滿足條件處往后全部保留,返回一個更小的迭代器。
函數原型如下:

dropwhile(predicate, iterable)

使用示例:

In [31]: from itertools import dropwhileIn [32]: a = dropwhile(lambda x: x> 5, [1,2,6,7,0])In [33]: for i in a:...:     print(i)...:     
1
2
6
7
0In [34]: a = dropwhile(lambda x: x> 5, [9,8,2,7,0])In [35]: for i in a:...:     print(i)...:     
2
7
0In [36]: 

5. take 迭代器

掃描列表,只要滿足條件就從可迭代對象中返回元素,直到不滿足條件為止,原型如下:

takewhile(predicate, iterable)

使用示例:

In [36]: from itertools import takewhileIn [37]: a = takewhile(lambda x:x>5, [9,8,2,7,0])In [38]: for i in a:...:     print(i)...:     
9
8In [39]: 

6. 加強版 zip

若可迭代對象的長度未對齊,將根據 fillvalue 填充缺失值,返回結果的長度等于更長的序列長度。

In [39]: from itertools import zip_longestIn [40]: list(zip_longest("abcd", "xy", fillvalue="-"))
Out[40]: [('a', 'x'), ('b', 'y'), ('c', '-'), ('d', '-')]In [41]: 

7. 笛卡爾積

笛卡爾積實現的效果,同下:

((x,y) for x in A for y in B)

使用示例:

In [41]: from itertools import productIn [42]: list(product("abcd", "12"))
Out[42]: 
[('a', '1'),('a', '2'),('b', '1'),('b', '2'),('c', '1'),('c', '2'),('d', '1'),('d', '2')]In [43]: 

8. 復制元素

repeat 實現復制元素 n 次,原型如下:

repeat(object[, times])

使用示例:

In [43]: from itertools import repeatIn [44]: list(repeat(2,3))
Out[44]: [2, 2, 2]In [45]: list(repeat([1,2],3))
Out[45]: [[1, 2], [1, 2], [1, 2]]In [46]: list(repeat({},3))
Out[46]: [{}, {}, {}]In [47]: 

總結

以上是生活随笔為你收集整理的Pyhton 内置 itertools 模块chain、accumulate、compress、drop、take等函数使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。