python迭代器以及itertools模块

迭代器       

      在python中,迭代器协议就是实现对象的__iter()方法和next()方法,其中前者返回对象本身,后者返回容器的下一个元素。实现了这两个方法的对象就是可迭代对象。迭代器是有惰性的,只有在使用时才会产生,这就为处理大量数据提供了好处,不同一次性把所有数据写入内存。下面自己写了一个迭代器,可以看到使用for循环可以处理自己编写的迭代器,实现了迭代器协议的对象,可以使用任何类似于for循环这样的迭代器工具。但是,看下面的输出,第二次输出为空,这是为什么呢?我们在使用list时,可以多次输出同一个对象,这和实现了自己实现了迭代器协议的对象有什么区别?

 1 class it(object):
 2     def __init__(self, n):
 3         self.a = 0
 4         self.n = n
 5 
 6     def __iter__(self):
 7         return self
 8 
 9     def next(self):
10         if self.a < self.n:
11             self.a += 1
12             return self.a
13         else:
14             raise StopIteration
15 
16 i=it(5)
17 for j in i:
18     print j,
19 print ''
20 print '------'
21 for j in i:
22     print j
23 # 1 2 3 4 5
24 # ------

      经过学习,得知,list等类型迭代器返回的是一个迭代器对象,不是返回了本身。那么就写了如下代码进行测试,经过打印输出可以看到,类TestIt的对象是可以反复使用的。那么又有一个问题了,没有实现next()方法的对象,还是迭代器对象吗?这是因为在使用it类时,是返回了迭代器对象的,把迭代的功能使用了it迭代器实现,也就是说相当于实现了迭代器协议。迭代器协议在python中很有用,python中有一个关于迭代器的模块itertools,下面我就学习一下itertools模块,看看有哪些惊喜!

1 class TestIt(object):
2     def __init__(self, a):
3         self.a = a
4 
5     def __iter__(self):
6         return it(self.a)

itertools

无限迭代器

1 count(),接受两个参数,第一个是开始的数字,第二个是步幅,默认从0开始,用法如下

1 import itertools as it
2 
3 c = it.count(10, 2)
4 for i in c:
5     if i > 20:
6         break
7     print i,
8 # 10 12 14 16 18 20

2 cycle(),接受一个参数,该参数是迭代器对象(列表,字符串等),会循环生成迭代器中的元素

1 c = it.cycle([1, 2, 3])
2 i = 1
3 for j in c:
4     if i > 7:
5         break
6     print j,
7     i += 1

3 repeat(),接受两个参数,用于生成第一个参数n次

1 for j in it.repeat([1, 2, 3], 4):
2     print j

有限迭代器,选取感觉自己常用的介绍下

1 chain(),接受多个迭代器对象作为参数,并把它们连接起来chain('abc', [1, 2, 3])

2 compress(data, selectors), 根据后面的参数过滤前面的参数,两个参数都需要是迭代器对象

dropwhile(pre, iterable),pre参数是一个函数,当pre(i)是Ture是,返回该项以及后面所有项

groupby(iterable[, keyfunc]),其中iterable 是一个可迭代对象,keyfunc 是分组函数,用于对 iterable 的连续项进行分组,如果不指定,则默认对 iterable 中的连续相同项进行分组,返回一个 (key, sub-iterator) 的迭代器。

ifilter(function or None, sequence),将 iterable 中 function(item) 为 True 的元素组成一个迭代器返回,如果 function 是 None,则返回 iterable 中所有计算为 True 的项

6 tee(iterable [,n]),tee 用于从 iterable 创建 n 个独立的迭代器,以元组的形式返回,n 的默认值是 2。

1 for j in it.tee('abc', 4):
2     print list(j)

组合生成器

permutations(iterable[, r]),用于生成一个排列,r是生成排列的元素长度,不指定则为默认长度

1 print list(it.permutations('abc'))
2 print list(it.permutations('abc', 2))
3 # [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
4 # [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

combinations(iterable, r), 求序列的组合,其中,r 指定生成组合的元素的长度,是必需的参数

3 combinations_with_replacement(iterable, r),生成的组合包含自身元素

1 print list(it.combinations_with_replacement('abc', 2))
2 # [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]

 

原文地址:https://www.cnblogs.com/qiaojushuang/p/6413994.html