Python标准库--itertools模块
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python标准库--itertools模块相关的知识,希望对你有一定的参考价值。
itertools模块:处理可迭代对象
chain()和islice()、tee()
chain:合并迭代器
islice:切割迭代器,start,end,step
tee:复制迭代器,新迭代器共享输入迭代器, 新迭代器之间不影响
from itertools import * # for i in chain([1, 2, 3], [‘a‘, ‘b‘, ‘c‘]): # print(i) # # for i in islice(count(), 0, 100, 10): # print(i) r = islice(count(), 5) i1, i2 = tee(r) # print(list(i1)) # print(list(i2)) for i in r: print(i) if i > 0: break for i in i1: print(i) if i > 1: break print(list(i1)) print(list(i2))
startmap()
values = [(0, 5), (1, 6), (2, 7)] for i in starmap(lambda x, y: (x, y, x * y), values): print(i) # (0, 5, 0) # (1, 6, 6) # (2, 7, 14)
count()、cycle()、repeat()
for i in count(): print(i) for i in cycle([‘a‘, ‘b‘, ‘c‘]): print(i) for i in repeat(2,5): print(i)
takewhile()、dropwhile()、filterfase()
takewhile:一旦条件为false,停止处理
dropwhile:条件为false,开始处理
filterfase:只处理条件为false
def should_drop(x): return x < 1 for i in dropwhile(should_drop, [-1, 0, 1, 2, -2]): print(i) def should_take(x): return x < 2 for i in takewhile(should_take, [-1, 0, 1, 2, -2]): print(i) def check_item(x): return x < 1 for i in filterfalse(check_item, [-1, 0, 1, 2, -2]): print(i)
groupby()
以上是关于Python标准库--itertools模块的主要内容,如果未能解决你的问题,请参考以下文章