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 ...
随机推荐
- 【Linux】使用xshell登陆时密码框为灰色,无法输入密码
使用xshell登陆时,出现以上情况,那么这到底值咋回事呢?经过查询以后发现是服务器端设置问题,解决办法如下: vi /etc/ssh/sshd_config 接着保存退出,然后重启sshd服务 se ...
- 浅谈struts2标签中的2个非经常常使用的标签的使用方法(radio和select)
1.如图所看到的我们须要在前台的页面通过radio和select将相应的数据库中的数据显示到选项其中,这也是我们做项目中常常须要做的,动态的显示,而不是静态的显示. 首先我们须要在页面中导入strut ...
- Devops成功的八大炫酷工具
原文链接:http://www.infoworld.com/article/3031009/devops/8-more-cool-tools-for-devops-success.html 为自动化和 ...
- Android中ListView分类
1 http://my.oschina.net/bv10000/blog/106436 2
- MyReport报表引擎2.7.8.8公布
支持嵌套子报表直接编辑保存,多个子报表同一时候存储在一个报表格式文件中,设计更简便,避免了嵌套报表的多个报表格式载入. watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5 ...
- Mongodb 的学习
传送门: # 官方网站 及 下载地址 https://www.mongodb.com/download-center/enterprise/releases # 之前简单学习的笔记http://www ...
- quartz项目中的运用
下面是之前项目中quartz的运用,我将它梳理出来. 测试类: public class OrdExpireTaskMain { public static void main(String[] ar ...
- graph小案例
(小案例,有五个人他们参见相亲节目,这个五个人分别是0,1,2,3,4,号选手,计算出追随者年龄大于被追随者年龄的人数和平均年龄) scala> import org.apache.spark. ...
- mongodb中批量将时间戳转变通用日期格式
1,官网提供的mongodb遍历脚本: 官方文档地址:https://docs.mongodb.org/manual/tutorial/remove-documents/ >var arr = ...
- start with git
Start with git 1.what is GitHub? GitHub is a code hosting platform for version control and collabora ...