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()

 

posted @ 2017-06-18 12:57  兔头咖啡  阅读(310)  评论(0编辑  收藏  举报


作者:兔头咖啡
出处:http://www.cnblogs.com/wj5633/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。