# Python的迭代器和生成器

Python的迭代器和生成器

1）next方法

2）__iter__方法

>>> i = iter('abc')
>>> i.next()
'a'
>>> i.next()
'b'
>>> i.next()
'c'
>>> i.next()
Traceback (most recent call last):
File "", line 1, in
StopIteration:

class MyIterator(object):
def __init__(self, step):
self.step = step
def next(self):
"""Returns the next element."""
if self.step==0:
raise StopIteration
self.step-=1
return self.step
def __iter__(self):
"""Returns the iterator itself."""
return self
for el in MyIterator(4):
print el
--------------------

3
2
1
0

def fibonacci():
a,b=0,1
while True:
yield b
a,b = b, a+b
fib=fibonacci()
print fib.next()
print fib.next()
print fib.next()
print [fib.next() for i in range(10)]
--------------------

1
1
2
[3, 5, 8, 13, 21, 34, 55, 89, 144, 233]

PEP Python Enhancement Proposal Python增强建议

tokenize模块
>>> import tokenize
>>> tokens.next()
(1, 'class', (1, 0), (1, 5), 'class MyIterator(object):/n')
>>> tokens.next()
(1, 'MyIterator', (1, 6), (1, 16), 'class MyIterator(object):/n')
>>> tokens.next()
(51, '(', (1, 16), (1, 17), 'class MyIterator(object):/n')

def power(values):
for value in values:
print 'powering %s' %value
yield value
for value in values:
if value%2==0:
yield value+3
else:
yield value+2
elements = [1,4,7,9,12,19]
print res.next()
print res.next()
--------------------

powering 1
3
powering 4
7

def psychologist():
while True:
print ("Don't ask yourself too much questions")
print "A that's good, go on"
print "Don't be so negative"
free = psychologist()
print free.next()
print free.send("Why I shouldn't ?")
print free.send("ok then i should find what is good for me")
--------------------

None
Don't be so negative
None
Don't ask yourself too much questions
None
A that's good, go on
None

|
6天前
|

Python中关于迭代器的使用

11 2
|
9天前
|

14 2
|
20天前
|
Python 容器
Python中迭代器的基本概念
【7月更文挑战第3天】
14 1
|
20天前
|
Python
Python中自定义迭代器
【7月更文挑战第3天】
11 1
|
20天前
|
Python
Python中创建迭代器
【7月更文挑战第3天】
15 1
|
22天前
|
Python
python解包迭代器或生成器
【7月更文挑战第1天】
17 3
|
21天前
|

Python的生成器（Generator）
【7月更文挑战第2天】
12 1
|
21天前
|
Python 容器
python 的迭代器（Iterator）
【7月更文挑战第2天】
10 1
|
22天前
|
Python
python解包迭代器或生成器
【7月更文挑战第1天】
14 1
|
9天前
|

MkDocs是一个用Python编写的快速、简单且易于定制的静态网站生成器
MkDocs是一个用Python编写的快速、简单且易于定制的静态网站生成器
9 0