首页 > 编程语言 > 详细

Python自动化开发从浅入深-语言基础(迭代器和生成器)

时间:2016-02-12 22:10:34      阅读:318      评论:0      收藏:0      [点我收藏+]
  • 迭代器的含义是我们可以在一个序列数的循环中一次只读取一个值,利用next方法读取下一个值,一直向前next读取,直到序列值读取完毕,并出现读取异常。
  • 而生成器则是一个迭代器执行的方法(函数功能)。

    --- next方法: 返回容器的下一个元素
    --- __iter__方法:返回迭代器自身

迭代器可使用内建的iter方法创建
>>> i = iter(abc)
>>> i.next()
a
>>> i.next()
b
>>> i.next()
c
>>> i.next()
Traceback (most recent call last):
  File "<string>", line 1, in <string>
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

二、生成器Generators
利用yield指令,允许停止函数并立即返回结果。
此函数保存其执行上下文,如果需要,可立即继续执行。
例如Fibonacci函数:
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
>>> reader = open(c:/temp/py1.py).next
>>> tokens=tokenize.generate_tokens(reader)
>>> 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
def adder(values):
  for value in values:
  print adding to %s %value
  if value%2==0:
  yield value+3
  else:
  yield value+2
elements = [1,4,7,9,12,19]
res = adder(power(elements))
print res.next()
print res.next()
--------------------
结果:
powering 1
adding to 1
3
powering 4
adding to 4
7

保持代码简单,而不是数据。
注意:宁可有大量简单的可迭代函数,也不要一个复杂的一次只计算出一个值的函数。

例子:
def psychologist():
  print Please tell me your problems
  while True:
  answer = (yield)
  if answer is not None:
  if answer.endswith(?):
  print ("Don‘t ask yourself too much questions")
  elif good in answer:
  print "A that‘s good, go on"
  elif bad in answer:
  print "Don‘t be so negative"
free = psychologist()
print free.next()
print free.send(I feel bad)
print free.send("Why I shouldn‘t ?")
print free.send("ok then i should find what is good for me")
--------------------
结果:
Please tell me your problems
None
Dont be so negative
None
Dont ask yourself too much questions
None
A thats good, go on
None

摘录实例(http://www.cnblogs.com/finallyliuyu/archive/2010/04/09/1708584.html)

 

Python自动化开发从浅入深-语言基础(迭代器和生成器)

原文:http://www.cnblogs.com/whiggzhaohong/p/5180945.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!