一、迭代器
介绍迭代器之前先看如下例子:
1
2
3
4
5
6
|
collections c1 = collections.Counter()
c1 c1.elements() d1 = c1.elements()
d1 |
输出结果:
1
2
|
Counter({ '2' : 5 , 'g' : 3 , '4' : 3 , 'e' : 2 , '3' : 2 , 'a' : 1 , '1' : 1 , 'd' : 1 , 'f' : 1 , 'q' : 1 , 's' : 1 , 'w' : 1 })
<itertools.chain object at 0x02570F30 >
|
发现c1.elements()居然打印不出具体结果。只给了一段说明,
即itertools.chain object at 0x02570F30,像这种情况下,说明
c1.elements()是一个迭代器,迭代器的结果只能通过循环来取出
这里可以用for循环来验证:
1
2
|
for n in c1.elements():
print n
|
输出结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
a
1
e
e
d
g
g
g
f
3
3
q
s
2
2
2
2
2
4
4
4
w
|
所以遇到迭代器功能的函数或者方法,一般取值用循环。进一步查看
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
c1.elements() class chain(__builtin__. object )
| chain( * iterables) - - > chain object
|
| Return a chain object whose . next () method returns
elements from the
| first iterable until it is exhausted, then elements
from the next
| iterable, until all of the iterables are exhausted.
|
| Methods defined here:
|
| __getattribute__(...)
| x.__getattribute__( 'name' ) < = = > x.name
|
|
| x.__iter__() < = = > iter (x)
|
| from_iterable(...)
| chain.from_iterable(iterable) - - > chain object
|
| Alternate chain() contructor taking a single
iterable argument
| that evaluates lazily.
|
| next (...)
| x. next () - > the next value, or raise StopIteration
|
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Data and other attributes defined here:
|
| __new__ = <built - in method __new__ of type object >
| T.__new__(S, ...) - > a new object with type S,
a subtype of T
|
从help(c1.elements())发现有一个方法
1
2
|
__iter__(...) x.__iter__() < = = > iter (x)
|
该方法是所有具有迭代功能函数必须具备的内置方法,换句话说有了这个内置方法
是其他函数或者方法具有迭代功能的前提条件
二、生成器
range不是生成器,xrange是生成器
readlines不是生成器,xreadlines是生成器
1
2
3
4
5
6
|
print range ( 10 )
输出结果: [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
print xrange ( 10 )
输出结果: xrange ( 10 )
|
生成器可以用程序连接数据库之间的连接池来进行理解:
当程序来连接数据库的时候,操作完数据库就会断开连接,如果在程序和数据库
之间设置一个连接池,该池子中已经有一些活跃的连接(一端跟数据库处于
建立连接状态),等着程序来连接,那么只要程序要访问数据库就可以直接连接
连接池即可。那么这也就是生成器的原理,生成器已经运行起来,只是没有在内存
中产生数据,如果有访问需求,则会立马在内存中创建数据。所以上述列子中的
xrange是生成器。接下来用for循环来取xrange(10)中是数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
for n in xrange ( 10 ):
print n
输出结果: 0
1
2
3
4
5
6
7
8
9
|
如果直接打印xrange(10),输出结果就是上述所示的:xrange(10)
本文转自027ryan 51CTO博客,原文链接:http://blog.51cto.com/ucode/1717231,如需转载请自行联系原作者