Python的迭代器和生成器使用实例

一、迭代器iterators

迭代器仅是一容器对象,它实现了迭代器协议。它有两个基本方法:

1)next方法
返回容器的下一个元素

2)__iter__方法
返回迭代器自身

迭代器可使用内建的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

二、生成器Generators

Python2.2起,生成器提供了一种简洁的方式帮助返回列表元素的函数来完成简单和有效的代码。
它基于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增强建议

立即学习“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
Don’t be so negative
None
Don’t ask yourself too much questions
None
A that’s good, go on
None

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2292382.html

(0)
上一篇 2025年2月28日 01:42:29
下一篇 2025年2月28日 01:42:52

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • python列表操作实例

    本文实例讲述了python列表操作的方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:class Node:   “””Single node in a data structure&…

    编程技术 2025年2月28日
    100
  • python操作gmail实例

    本文实例讲述了python操作gmail的方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:import imaplib, re class pygmail(object):    def __init__(self):…

    编程技术 2025年2月28日
    200
  • Python实现一个简单的MySQL类

    本文实例讲述了python实现一个简单的mysql类。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:#!/usr/bin/env python# -*- coding:utf-8 -*-# Created on 2011-…

    编程技术 2025年2月28日
    200
  • python实现多线程暴力破解登陆路由器功能代码分享

    运行时请在其目录下添加user.txt passwd.txt两文件。否则会报错。程序没有加异常处理。代码比较挫….. 复制代码 代码如下:#coding:utf-8- import base64 import urllib2 i…

    编程技术 2025年2月28日
    200
  • Python基类函数的重载与调用实例分析

    本文实例讲述了python基类函数的重载与调用方法。分享给大家供大家参考。具体分析如下: 刚接触Python语言的时间不长,对于这个语言的很多特性并不是很了解,有很多用法都是还不知道。今天想着写一个Python面向对象编程时的继承中的函数调…

    编程技术 2025年2月28日
    200
  • Python类的专用方法实例分析

    本文实例讲述了python类的专用方法。分享给大家供大家参考。具体分析如下: Python 类可以定义专用方法,专用方法是在特殊情况下或当使用特别语法时由 Python 替你调用的,而不是在代码中直接调用(象普通的方法那样)。 1. __i…

    编程技术 2025年2月28日
    200
  • Python连接mssql数据库编码问题解决方法

    python一直对中文支持的不好,最近老遇到编码问题,而且几乎没有通用的方案来解决这个问题,但是对常见的方法都试过之后,发现还是可以解决的,下面总结了常用的支持中文的编码问题(这些方法中可能其中一个就能解决问题,也可能是多个组合)。 (1)…

    编程技术 2025年2月28日
    200
  • Python中optparse模块使用浅析

    最近遇到一个问题,是指定参数来运行某个特定的进程,这很类似linux中一些命令的参数了,比如ls -a,为什么加上-a选项会响应。optparse模块实现的也是类似的功能,它是为脚本传递命令参数。 使用此模块前,首先需要导入模块中的类Opt…

    2025年2月28日
    200
  • Python解决鸡兔同笼问题的方法

    本文实例讲述了python解决鸡兔同笼问题的方法,分享给大家供大家参考。具体分析如下: 问题描述 一个笼子里面关了鸡和兔子(鸡有 2 只脚,兔子有 4 只脚,没有例外)。已经知道了笼 子里面脚的总数 a,问笼子里面至少有多少只动物,至多有多…

    编程技术 2025年2月28日
    200
  • Python列表计数及插入实例

    本文实例讲述了python列表计数及插入的用法。分享给大家供大家参考。具体如下: 复制代码 代码如下:word=[‘a’,’b’,’c’,’d’…

    编程技术 2025年2月28日
    200

发表回复

登录后才能评论