itertools内置库
Posted fuzzier
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了itertools内置库相关的知识,希望对你有一定的参考价值。
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
.
在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
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
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
分类
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‘,)
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 . .
9 itertools.cycle(iterable)
将迭代器进行无限迭代
import itertools for each in itertools.cycle(‘ab‘): print each
output:
a
b
a
b
.
以上是关于itertools内置库的主要内容,如果未能解决你的问题,请参考以下文章
这段代码很Pythonic | 相见恨晚的 itertools 库