码迷,mamicode.com
首页 > 编程语言 > 详细

Python标准库--itertools模块

时间:2017-06-18 14:16:00      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:迭代   int   false   turn   should   fas   合并   lambda   drop   

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模块

标签:迭代   int   false   turn   should   fas   合并   lambda   drop   

原文地址:http://www.cnblogs.com/wj5633/p/7044052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!