python cookbook 迭代器与生成器
代理迭代
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 迭代器与生成器的更多相关文章
- python基础—迭代器、生成器
python基础-迭代器.生成器 1 迭代器定义 迭代的意思是重复做一些事很多次,就像在循环中做的那样. 只要该对象可以实现__iter__方法,就可以进行迭代. 迭代对象调用__iter__方法会返 ...
- python之迭代器与生成器
python之迭代器与生成器 可迭代 假如现在有一个列表,有一个int类型的12345.我们循环输出. list=[1,2,3,4,5] for i in list: print(i) for i i ...
- Python之迭代器和生成器
Python 迭代器和生成器 迭代器 Python中的迭代器为类序列对象(sequence-like objects)提供了一个类序列的接口,迭代器不仅可以对序列对象(string.list.tupl ...
- 【Python】迭代器、生成器、yield单线程异步并发实现详解
转自http://blog.itpub.net/29018063/viewspace-2079767 大家在学习python开发时可能经常对迭代器.生成器.yield关键字用法有所疑惑,在这篇文章将从 ...
- python的迭代器、生成器、装饰器
迭代器.生成器.装饰器 在这个实验里我们学习迭代器.生成器.装饰器有关知识. 知识点 迭代器 生成器 生成器表达式 闭包 装饰器 实验步骤 1. 迭代器 Python 迭代器(Iterators)对象 ...
- Python之迭代器,生成器
迭代器 1.什么是可迭代对象 字符串.列表.元组.字典.集合都可以被for循环,说明他们都是可迭代的. from collections import Iterable l = [1,2,3,4] t ...
- python之迭代器、生成器与面向过程编程
目录 一 迭代器 二 生成器 三 面向过程编程 一.迭代器 1.迭代器的概念理解 ''' 迭代器从字面上理解就是迭代的工具.而迭代是每次的开始都是基于上一次的结果,不是周而复始的,而是不断发展的. ' ...
- day13 python学习 迭代器,生成器
1.可迭代:当我们打印 print(dir([1,2])) 在出现的结果中可以看到包含 '__iter__', 这个方法,#次协议叫做可迭代协议 包含'__iter__'方法的函数就是可迭代函数 ...
- Python之迭代器及生成器
一. 迭代器 1.1 什么是可迭代对象 字符串.列表.元组.字典.集合 都可以被for循环,说明他们都是可迭代的. 我们怎么来证明这一点呢? from collections import Itera ...
随机推荐
- iOS语言本地化,中文显示
尽管一直相信xcode肯定提供有语言本地化的设置地方,可是一直也没凑着去改.非常多的汉化,还是使用代码去控制:比方navagition的return使用代码改动为"返回"! 近期在 ...
- 通过小书匠编辑器让印象笔记和evernote支持markdown编辑
a:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2p ...
- Caused by: java.lang.ClassNotFoundException: Didn't find class "** *** ** **" on path: DexPathList[[zip file "/data/app/*** *** ***-2/base.apk"],nativeLibraryDirectories
Caused by: java.lang.ClassNotFoundException: Didn't find class "** *** ** **" on path: Dex ...
- Windows安装Redis的php扩展
Redis是一种常用的非关系型数据库,主要用作数据缓存,数据保存形式为key-value,键值相互映射.它的数据存储跟MySQL不同,它数据存储在内存之中,所以数据读取相对而言很快,用来做高并发非常不 ...
- java之JDK动态代理
© 版权声明:本文为博主原创文章,转载请注明出处 JDK动态代理: JDK动态代理就是在程序运行期间,根据java的反射机制自动的帮我们生成相应的代理类 优势: - 1. 业务类只需要关注业务逻辑本身 ...
- centos root登录password 忘记解决的方法
Centos系统 登陆root忘记password 解决方式: (1)开机启动系统,在进入linux系统之前按键Esc 进入例如以下界面:(须要注意:Centos是安装在虚拟机里面的话,须要将鼠标点进 ...
- 计算机图形学(二)输出图元_6_OpenGL曲线函数_2_中点画圆算法
中点画圆算法 如同光栅画线算法,我们在每一个步中以单位间隔取样并确定离指定圆近期的像素位置.对于给定半径r和屏幕中心(xc,yc),能够先使用算法计算圆心在坐标原点(0, 0)的圆的像素 ...
- JLink defective
下载了最新的JLink V622g,打开JLink命令行后,提示以下信息 The connected J-Link is defective,Proper operation cannot be gu ...
- NPTL LinuxThreads
Linux 线程模型的比较:LinuxThreads 和 NPTL 进行移植的开发人员需要了解的关键区别摘要 Vikram Shukla 2006 年 8 月 28 日发布 WeiboGoogle+用 ...
- IP地址、子网掩码、网关的关系
网络管理中的IP地址.子网掩码和网关是每个网管必须要掌握的基础知识,只有掌握它,才能够真正理解TCP/IP协议的设置.以下我们就来深入浅出地讲解什么是子网掩码. IP地址的结构 要想理解什么是子网掩码 ...