代理迭代

  a = [1, 2, 3]
for i in iter(a):
print(i)
for i in a.__iter__():
print(i)

这里的两个方法是一样的,调用iter()其实就是简单的调用了对象的__iter__()方法。

使用生成器创建新的迭代器

  def frange(start, stop, increment):
x = start
while x < stop:
yield x
x += increment
for n in frange(0, 4, 0.5):
print(n)
print(list(frange(0, 4, 0.5)))

看下面这个

>>> def countdown (n):
... print ('Starting to count from', n)
... while n > 0:
... yield n
... n -= 1
... print ('Done!')
...
>>> # Create the generator, notice no output appears
>>> c = countdown(3)
>>> c
<generator object countdown at 0x1006a0af0>>>> next(c)
Starting to count from 3
3>>> next(c)
2>>> next(c)
1>>> next(c)
Done!
Traceback (most recent call last):
File "<stdin>", line 1, in < module >
StopIteration

一个生成器函数主要特征是它只会回应在迭代中使用到的 next 操作。 一旦生成器函数返回退出,迭代终止。我们在迭代中通常使用的for语句会自动处理这些细节,所以你无需担心。

  def frange(start, stop, increment):
x = start
while x < stop:
yield x
x += increment
for n in frange(, , 0.5):
print(n)
print(list(frange(, , 0.5)))

反向迭代

  a = [1, 2, 3, 4]
for x in reversed(a):
print(x, end=' ')

主要想说的是,对象重写__reversed__()方法即可调用reversed()进行反向迭代

itertools的一些使用

  def count(n):
while True:
yield n
n += 1
c = count(0)
import itertools
for x in itertools.islice(c, 10, 20):
print(x, end=" ") with open('test.txt') as f:
for line in f:
print(line, end='')
print(format('开始部分的注释不显示', '*>30'))
with open('test.txt') as f:
for line in itertools.dropwhile(lambda line: line.startswith('#'), f):
print(line, end='') items = ['a', 'b', 'c']
#items的所有可能组合,不包含相同元素
for p in itertools.permutations(items):
print(p, end=' ')
print()
#指定长度的所有排序
for p in itertools.permutations(items, 2):
print(p, end=' ')

如果遇到一些复杂的迭代器的使用,可以先看看itertools里有没有可用的方法。

同时迭代多个序列

  a = [1, 2, 3]
b = ['w', 'x', 'y', 'z']
for i in zip(a,b):
print(i)
输出:
(1, 'w')
(2, 'x')
(3, 'y')
for i in itertools.zip_longest(a, b):
print(i)
输出:
(1, 'w')
(2, 'x')
(3, 'y')
(None, 'z')

不同序列上的迭代

  import itertools
a = [1, 2, 3, 4]
b = ['x', 'y', 'z']
for x in itertools.chain(a, b):
print(x)

这样比 a + b 在进行迭代要好很多

展开嵌套的序列

  from collections import Iterable
def flattern(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flattern(x)
else:
yield x
items = [1, 2, [3, 4, [5, 'hello world'], 7], 8]
for x in flattern(items):
print(x, end=' ')

def count(n):    while True:      yield n      n += 1  c = count(0)  import itertools  for x in itertools.islice(c, 10, 20):    print(x, end=" ")      with open('test.txt') as f:    for line in f:      print(line, end='')  print(format('开始部分的注释不显示', '*>30'))  with open('test.txt') as f:    for line in itertools.dropwhile(lambda line: line.startswith('#'), f):      print(line, end='')        items = ['a', 'b', 'c']  #items的所有可能组合,不包含相同元素  for p in itertools.permutations(items):    print(p, end=' ')  print()  #指定长度的所有排序  for p in itertools.permutations(items, 2):    print(p, end=' ')

python cookbook 迭代器与生成器的更多相关文章

  1. python基础—迭代器、生成器

    python基础-迭代器.生成器 1 迭代器定义 迭代的意思是重复做一些事很多次,就像在循环中做的那样. 只要该对象可以实现__iter__方法,就可以进行迭代. 迭代对象调用__iter__方法会返 ...

  2. python之迭代器与生成器

    python之迭代器与生成器 可迭代 假如现在有一个列表,有一个int类型的12345.我们循环输出. list=[1,2,3,4,5] for i in list: print(i) for i i ...

  3. Python之迭代器和生成器

    Python 迭代器和生成器 迭代器 Python中的迭代器为类序列对象(sequence-like objects)提供了一个类序列的接口,迭代器不仅可以对序列对象(string.list.tupl ...

  4. 【Python】迭代器、生成器、yield单线程异步并发实现详解

    转自http://blog.itpub.net/29018063/viewspace-2079767 大家在学习python开发时可能经常对迭代器.生成器.yield关键字用法有所疑惑,在这篇文章将从 ...

  5. python的迭代器、生成器、装饰器

    迭代器.生成器.装饰器 在这个实验里我们学习迭代器.生成器.装饰器有关知识. 知识点 迭代器 生成器 生成器表达式 闭包 装饰器 实验步骤 1. 迭代器 Python 迭代器(Iterators)对象 ...

  6. Python之迭代器,生成器

    迭代器 1.什么是可迭代对象 字符串.列表.元组.字典.集合都可以被for循环,说明他们都是可迭代的. from collections import Iterable l = [1,2,3,4] t ...

  7. python之迭代器、生成器与面向过程编程

    目录 一 迭代器 二 生成器 三 面向过程编程 一.迭代器 1.迭代器的概念理解 ''' 迭代器从字面上理解就是迭代的工具.而迭代是每次的开始都是基于上一次的结果,不是周而复始的,而是不断发展的. ' ...

  8. day13 python学习 迭代器,生成器

    1.可迭代:当我们打印 print(dir([1,2]))   在出现的结果中可以看到包含 '__iter__', 这个方法,#次协议叫做可迭代协议 包含'__iter__'方法的函数就是可迭代函数 ...

  9. Python之迭代器及生成器

    一. 迭代器 1.1 什么是可迭代对象 字符串.列表.元组.字典.集合 都可以被for循环,说明他们都是可迭代的. 我们怎么来证明这一点呢? from collections import Itera ...

随机推荐

  1. UE4射击小游戏原型

    尝试使用了下blueprint,不知道是bug还是不熟悉,blueprint有些地方运行的跟逻辑不太一样.不管ue4目前,快速做原型倒是蛮方便的.就等着官方发更多教程讲述关于新的matinee,Nav ...

  2. MATLAB 2014a 在Mac os x yosemite 10.10 Retina显示模糊的解决的方法

    恐怕非常多童鞋在升级了yosemite之后都遇到了Matlab的问题. 之前转载的一篇文章写了安装的方法,本文说一下解决Retina屏显示模糊的办法. 那么因为Matlab 2014a使用自带的jav ...

  3. Rabbitmq消息队列(一) centos下安装rabbitmq

    1.简介 AMQP,即Advanced Message Queuing Protocol,高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计.消息中间件主要用于组件之间的解耦,消息的 ...

  4. js事件之onmousedown和onmouseup

    <!DOCTYPE html> <html> <head> <script> function mouseDown() { document.getEl ...

  5. sublime livereload插件

    1.首先在chrome商店下载livereload 安装之后记得在 chrome 的 扩展程序 里面 勾上 允许访问文件地址 2.sublime text 3 中下载插件 Livereload 3.配 ...

  6. maven设置本地仓库地址和设置国内镜像

    <?xml version="1.0" encoding="UTF-8"?> <!-- 英文注释已经被删除了,直接修改本地仓库地址用就行了. ...

  7. Atitit.go语言golang语言的新的特性  attilax总结

    Atitit.go语言golang语言的新的特性  attilax总结 1. 继承树less  动态接口1 1.1. 按照书中说的,Go语言具有以下的特征,下面我们分别来进行介绍.  q 自动垃圾回收 ...

  8. Python内置函数之sorted()

    sorted(iterable,*,key=None,reverse=False) 对可迭代对象进行排序,默认ASCII进行排序. 例子: sorted(iterable,*,key=None,rev ...

  9. [译]GLUT教程 - 重整子窗体

    Lighthouse3d.com >> GLUT Tutorial >> Subwindows >> Reshape Subwindows 重整函数的回调需要处理两 ...

  10. apache占用内存高解决办法

    我用512M的vps,访问量不大,但内存占用很大,甚至宕机. 我用top,然后shitf+m发现,httpd占用内存极大.经过网上找资料设置后,用过一段时间终于没再出现内存问题了. 首先查找配置文件的 ...