Pyhton 内置 itertools 模块chain、accumulate、compress、drop、take等函数使用
Python 內(nèi)置的 itertools 模塊使用了 yield 生成器。
1. chain 拼接迭代器
chain 函數(shù)實現(xiàn)元素拼接,原型如下,參數(shù) * 表示可變的參數(shù):
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 累積迭代器
累積迭代器返回可迭代對象的累積迭代器,函數(shù)原型:
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 的參數(shù)個數(shù)要求為 2,根據(jù) 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 函數(shù),功能類似于漏斗功能,所以稱它為漏斗迭代器,原型:
compress(data, selectors)
經(jīng)過 selectors 過濾后,返回一個更小的迭代器。
In [29]: a = compress("helloworld", [1,0,1,0])In [30]: for i in a:...: print(i)...:
h
lIn [31]:
compress 返回元素個數(shù),等于兩個參數(shù)中較短序列的長度。
4. drop 迭代器
掃描可迭代對象 iterable ,從不滿足條件處往后全部保留,返回一個更小的迭代器。
函數(shù)原型如下:
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
若可迭代對象的長度未對齊,將根據(jù) 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. 笛卡爾積
笛卡爾積實現(xiàn)的效果,同下:
((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 實現(xiàn)復制元素 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等函数使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 不明原因不孕试管婴儿
- 下一篇: 古钱币多少钱啊?