itertools內置庫
阿新 • • 發佈:2017-09-02
cat 分類 map() 等於 code -a imap one 遞增
1 itertools.chain(*iterable)
將多個序列作為一個單獨的序列返回
import itertools for ele in itertools.chain(‘We‘, ‘ are ‘, ‘ champion.‘): print ele
output:
W
e
a
r
e
c
h
a
m
p
i
o
n
.
View Code
在iter中添加判斷類
2 itertools.compress(data, selector)
返回selector為True的data對應元素
import itertools for ele in itertools.compress(‘qwer‘, [1,0,1,1]): print ele
output:
q
e
r
View Code
3 itertools.ifiter(predicate, iterable)
返回predicate結果為True的元素叠代器,如果predicate為None,則返回所有iterable中為True的項
import itertools for ele in itertools.ifilter(lambda x: x > 5, range(8)): print ele
ouput:
6
7
View Code
4 itertools.ifterfalse(predicate, iterable)
與itertools.ifiter()正好相反
5 itertools.takewhile(predicate, iterable)
如果predicate為真,則返回iterable元素,如果為假則不再返回,break.
import itertools for ele in itertools.takewhile(lambda x: x < 5, range(8)): print ele
ouput:
0
1
2
3
4
View Code
分類
6 itertools.groupby(iterable[,key])
返回一組(key,itera),key為iterable的值,itera為等於key的所有項
註意:iterable需要先進行sort
import itertools for key, ele in itertools.groupby([‘abc‘, ‘awe‘, ‘bjf‘, ‘caf‘, ‘bjf‘], key=lambda x: x[0]): print key, tuple(ele)
output: a (‘abc‘, ‘awe‘) b (‘bjf‘,) c (‘caf‘,) b (‘bjf‘,)View Code
list變為iterable
7 itertools.imap(function,*iterables)
相當於叠代器方式的map()
8 itertools.islice(iterable, start,stop[,step])
相當於叠代器方式的切片操作
無限遞增
8 itertools.count(start=0,step=1)
返回以start開始,step遞增的序列,無限遞增
import itertools for each in itertools.count(start=0, step=2): print each
output: 1 2 3 . .View Code
9 itertools.cycle(iterable)
將叠代器進行無限叠代
import itertools for each in itertools.cycle(‘ab‘): print each
output:
a
b
a
b
.
View Code
itertools內置庫