当前位置:网站首页>How to understand Python iterators and generators?
How to understand Python iterators and generators?
2020-11-06 20:07:00 【SXXpenguin】
How to understand Python Iterators and generators ? stay Python in , Use for ... in ... It can be done to list、tuple、set and dict Data types are iterated , You can filter out all the data . as follows :
for element in [1, 2, 3]:
print(element)
for element in (1, 2, 3):
print(element)
for key in {'one':1, 'two':2}:
print(key)
for char in "123":
print(char)
for line in open("myfile.txt"):
print(line, end='')
1、 iterator
The string , list , Use built-in functions iter Convert to an iteratable object , Use next keyword , Iteratable objects take one value at a time . Like the following code :
nums = [1,2,3,4]
nums = iter(nums)
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))
Output
1
2
3
4
If it exceeds the length of the data , Will be an error StopIteration
nums = [1,2,3,4]
nums = iter(nums)
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums)) # Over data length , Report errors StopIteration
2、 generator
Using generators, you can create iterators . The generator mainly uses yeild keyword , Every time you call next When it comes to yeild The definition of the corresponding . for example : We need to take 10~20 Data between , In steps of 2, You can use the following code
for x in range(10,20,2):
print(x)
But if the step size is set to 0.5, The following code :
for x in range(10,20,0.5):
print(x)
Will be an error
TypeError: 'float' object cannot be interpreted as an integer
This is the time , We can use The generator comes from defining a function
def drange(start,stop,step):
x = start
while x< stop:
yield x
x += step
for x in drange(10,20,0.5):
print(x)
Another example :
Given a string , Flashback to arrange :
def reverse(data):
for x in range(len(data)-1,-1,-1):
yield data[x]
for x in reverse('gold'):
print(x)
See here , I believe that we can understand Python Iterators and generators have a certain understanding . More about dry goods , In the erudite Valley IT Training platform , From zero basis to advanced promotion, the learning content of each stage of learning is waiting for you !
Zhengzhou painless people hospital which good http://fk.zztjyy.com/
Zhengzhou see gynecology which hospital is good http://www.zztjfk.com/
Zhengzhou see gynecology which good http://www.xasgfuke.cn/
版权声明
本文为[SXXpenguin]所创,转载请带上原文链接,感谢
边栏推荐
- If PPT is drawn like this, can the defense of work report be passed?
- Pattern matching: The gestalt approach一种序列的文本相似度方法
- 用一个例子理解JS函数的底层处理机制
- Word segmentation, naming subject recognition, part of speech and grammatical analysis in natural language processing
- 一篇文章带你了解CSS对齐方式
- 文件过多时ls命令为什么会卡住?
- Five vuex plug-ins for your next vuejs project
- StickEngine-架构12-通信协议
- 5.5 controlleradvice notes - SSM in depth analysis and project practice
- Simple summary of front end modularization
猜你喜欢

一篇文章教会你使用HTML5 SVG 标签

一篇文章教会你使用Python网络爬虫下载酷狗音乐

Flink的DataSource三部曲之一:直接API

With the advent of tensorflow 2.0, can pytoch still shake the status of big brother?

Discussion on the technical scheme of text de duplication (1)

01. SSH Remote terminal and websocket of go language

理解格式化原理

零基础打造一款属于自己的网页搜索引擎

Elasticsearch数据库 | Elasticsearch-7.5.0应用搭建实战

axios学习笔记(二):轻松弄懂XHR的使用及如何封装简易axios
随机推荐
Chainlink brings us election results into blockchain everipedia
What if the front end doesn't use spa? - Hacker News
It is really necessary to build a distributed ID generation service
FastThreadLocal 是什么鬼?吊打 ThreadLocal 的存在!!
Azure data factory (3) integrate azure Devops to realize CI / CD
Details of dapr implementing distributed stateful service
A course on word embedding
Electron application uses electronic builder and electronic updater to realize automatic update
Pollard's Rho algorithm
The road of C + + Learning: from introduction to mastery
一路踩坑,被迫聊聊 C# 代码调试技巧和远程调试
Building and visualizing decision tree with Python
Network security engineer Demo: the original * * is to get your computer administrator rights! [maintain]
Word segmentation, naming subject recognition, part of speech and grammatical analysis in natural language processing
What is the difference between data scientists and machine learning engineers? - kdnuggets
给字节的学姐讲如何准备“系统设计面试”
【字节跳动 秋招岗位开放啦】Ohayoo!放学别走,我想约你做游戏!!!
Analysis of etcd core mechanism
What are Devops
What to do if you are squeezed by old programmers? I don't want to quit