博客
关于我
python~迭代器,生成器(2)
阅读量:538 次
发布时间:2019-03-09

本文共 667 字,大约阅读时间需要 2 分钟。

生成器与迭代器的区别

在程序编程中,生成器和迭代器是常见的概念,但二者的区别容易引起混淆。一个重要的原则是:生成器一定是迭代器,但迭代器不一定是生成器。

迭代器的定义

迭代器是能够通过next()函数获取下一个值的对象。利用isinstance()函数可以判断一个对象是否为迭代器。例如:

from collections import Iteratorisinstance((x for x in range(10)), Iterator) → Trueisinstance([], Iterator) → Falseisinstance({}, Iterator) → Falseisinstance('abc', Iterator) → Falseisinstance(100, Iterator) → False

iter()函数的作用

虽然列表(如list)、字典和字符串等数据类型属于Iterable,但它们并不是迭代器。要将它们转换为迭代器,可以使用iter()函数:

isinstance(iter([]), Iterator) → Trueisinstance(iter('abc'), Iterator) → True

总结

:valuearea>

任何可作用于for循环的对象都是Iterable;

任何可作用于next()函数的对象都是Iterator。

虽然集合数据类型如listdictstr是Iterable,但它们本身不是Iterator。通过iter()函数可以将它们转换为Iterator对象。

转载地址:http://hfaiz.baihongyu.com/

你可能感兴趣的文章
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>