Comments (2)
generator是特殊的迭代器
from python_interview_question.
迭代器是遵循迭代协议的对象。用户可以使用 iter() 以从任何序列得到迭代器(如 list, tuple, dictionary, set 等)。另一个方法则是创建一个另一种形式的迭代器 —— generator 。要获取下一个元素,则使用成员函数 next()(Python 2)或函数 next() function (Python 3) 。当没有元素时,则引发 StopIteration 此例外。若要实现自己的迭代器,则只要实现 next()(Python 2)或 next()( Python 3)
生成器(Generator),只是在需要返回数据的时候使用yield语句。每次next()被调用时,生成器会返回它脱离的位置(它记忆语句最后一次执行的位置和所有的数据值)
区别: 生成器能做到迭代器能做的所有事,而且因为自动创建iter()和next()方法,生成器显得特别简洁,而且生成器也是高效的,使用生成器表达式取代列表解析可以同时节省内存。除了创建和保存程序状态的自动方法,当发生器终结时,还会自动抛出StopIteration异常。 官方介绍:https://docs.python.org/3/tutorial/classes.html#iterators
我个人觉得这段问题不大
from python_interview_question.
Related Issues (20)
- GIL锁不是只有CPython才有 HOT 3
- 22题疑问
- 29题空格的问题
- 想转载怎么联系作者 HOT 3
- 18.反转一个整数,例如-123 --> -321
- 2.补充缺失的代码
- 13.请写出一段python代码实现删除list里面的重复元素? HOT 2
- 67-print c 输出是否有误
- 88一行代码有误,结果多另一个空list,可以更改为:
- @ 28 转换 “123”到123
- 遍历文件,可以考虑pathlib HOT 1
- 一般面试的话写单例最好写出线程安全的模式 HOT 1
- py 面试 HOT 1
- ### 29.Given an array of integers 第一个例子死循环 HOT 1
- ### 29.Given an array of integers 第一个解决方案死循环 HOT 1
- 72 题是错误的 HOT 1
- Python3基本数据类型描述有误 HOT 1
- 1.有一个jsonline格式的文件file.txt大小约为10K HOT 1
- 53题解释不全
- 请写出打印结果和存在的问题
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from python_interview_question.