当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
- 每个大火的“线上狼人杀”平台,都离不开这个新功能
- Analysis of query intention recognition
- keras model.compile Loss function and optimizer
- 6.6.1 localeresolver internationalization parser (1) (in-depth analysis of SSM and project practice)
- Mac installation hanlp, and win installation and use
- 用一个例子理解JS函数的底层处理机制
- Pollard's Rho algorithm
- 快速排序为什么这么快?
- 前端工程师需要懂的前端面试题(c s s方面)总结(二)
- [actual combat of flutter] pubspec.yaml Configuration file details
猜你喜欢

Free patent download tutorial (HowNet, Espacenet)

这个项目可以让你在几分钟快速了解某个编程语言

每个大火的“线上狼人杀”平台,都离不开这个新功能
![[C / C + + 1] clion configuration and running C language](/img/5b/ba96ff4447b150f50560e5d47cb8d1.jpg)
[C / C + + 1] clion configuration and running C language

Mac installation hanlp, and win installation and use

Windows 10 tensorflow (2) regression analysis of principles, deep learning framework (gradient descent method to solve regression parameters)
![Network security engineer Demo: the original * * is to get your computer administrator rights! [maintain]](/img/14/ede1ffa7811dbc2a5b15b9a7b17a5e.jpg)
Network security engineer Demo: the original * * is to get your computer administrator rights! [maintain]

Python基础变量类型——List浅析

Three Python tips for reading, creating and running multiple files

游戏主题音乐对游戏的作用
随机推荐
[C] (original) step by step teach you to customize the control element - 04, ProgressBar (progress bar)
Network security engineer Demo: the original * * is to get your computer administrator rights! [maintain]
The road of C + + Learning: from introduction to mastery
每个大火的“线上狼人杀”平台,都离不开这个新功能
How to demote domain controllers and later in Windows Server 2012
TensorFlow中的Tensor是什么?
The difference between gbdt and XGB, and the mathematical derivation of gradient descent method and Newton method
Natural language processing - BM25 commonly used in search
一篇文章带你了解CSS 渐变知识
Natural language processing - wrong word recognition (based on Python) kenlm, pycorrector
The dynamic thread pool in Kitty supports Nacos and Apollo multi configuration centers
Construction of encoder decoder model with keras LSTM
Details of dapr implementing distributed stateful service
DRF JWT authentication module and self customization
仅用六种字符来完成Hello World,你能做到吗?
Chainlink brings us election results into blockchain everipedia
FastThreadLocal 是什么鬼?吊打 ThreadLocal 的存在!!
MeterSphere开发者手册
axios学习笔记(二):轻松弄懂XHR的使用及如何封装简易axios
消息队列(MessageQueue)-分析