Python学习之内建模块(3):itertools

itertools给我们提供了很多有用的用于迭代对象的函数.

[0]:cycle用来循环一个序列

import itertools
c = itertools.cycle([1,2,3,4,5])
for i in c:print(i)

[1]:count用来迭代自然数

import itertools
c = itertools.count(30000)
for i in c:print(i)

[2]:takewhile用来截断:

Return successive entries from an iterable as long as the predicate evaluates to true for each entry.意思就是从从第一个元素开始直到找到一个不满足条件的元素.有可能为空

import itertools
c = itertools.count(1)
s = itertools.takewhile(lambda x: (x%7)<=5,c)
print(list(s))

[3]groupby函数,用来找出相邻’重复’的元素.

import itertools,math
c = [1,4,81,4,9,6,7,8,36,196,17,29,13]

s = itertools.groupby(c,lambda x:math.sqrt(x)==int(math.sqrt(x)))
for key,group in s:print(key,list(group))

你可能感兴趣的:(Python学习之内建模块(3):itertools)