浅谈python迭代器
作者:bloke 时间:2023-07-21 21:56:47
1、yield,将函数变为 generator (生成器)
例如:斐波那契数列
def fib(num):
a, b, c = 1, 0, 1
while a <= num:
yield c
b, c = c, b + c
a += 1
for n in fib(10):
print(n, end=' ')
# 1 1 2 3 5 8 13 21 34 55
2、Iterable
所有可以使用for循环的对象,统称为 Iterable (可迭代)
from collections import Iterable, Iterator
print(isinstance(fib(10), Iterable))
print(isinstance(range(10), Iterable))
# True
# True
3、Iterator
可以使用next() <__next__()> 函数调用并且不断返回下一个值的对象成为 Iterator (迭代器),表示一个惰性计算的序列。
list, dict, str是Iterable,不是Iterator:
from collections import Iterator
print(isinstance(list(), Iterator))
# False
但是可以通过iter()函数将其变为Iterator:
print(isinstance(iter(list()), Iterator))
# True
来源:http://www.cnblogs.com/bloke/p/7801480.html
标签:python,迭代器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python QQBot库的QQ聊天机器人
2022-03-18 23:29:30
![](https://img.aspxhome.com/file/2023/0/64720_0s.jpg)
Python环境使用OpenCV检测人脸实现教程
2022-01-24 11:31:21
![](https://img.aspxhome.com/file/2023/4/68474_0s.jpg)
Python变量、数据类型、数据类型转换相关函数用法实例详解
2021-03-29 08:30:35
![](https://img.aspxhome.com/file/2023/3/65443_0s.png)
利用python如何在前程无忧高效投递简历
2022-10-26 22:33:02
![](https://img.aspxhome.com/file/2023/1/128511_0s.png)
mysql 8.0.11安装配置方法图文教程
2024-01-27 17:22:08
![](https://img.aspxhome.com/file/2023/7/77217_0s.jpg)
JavaScript高级程序设计 阅读笔记(十七) js事件
2024-04-19 09:55:17
SQL SERVER 2014 安装图解教程(含SQL SERVER 2014下载)
2024-01-16 05:16:07
![](https://img.aspxhome.com/file/2023/1/113591_0s.png)
vue3动态添加路由
2024-05-13 09:08:34
![](https://img.aspxhome.com/file/2023/6/126646_0s.png)
Python爬虫beautifulsoup4常用的解析方法总结
2022-09-01 11:58:54
JavaScript拖动层Div代码
2024-04-16 09:46:48
![](https://img.aspxhome.com/file/2023/4/136554_0s.png)
也谈 CSS Sprites
2009-10-06 15:14:00
![](https://img.aspxhome.com/file/UploadPic/200910/6/1254278481253-97s.png)
javascript unicode与GBK2312(中文)编码转换方法
2024-04-17 10:09:36
vue 循环动态设置ref并获取$refs方式
2023-07-02 17:00:18
![](https://img.aspxhome.com/file/2023/2/139882_0s.png)
解决antd Form 表单校验方法无响应的问题
2024-05-28 16:00:23
![](https://img.aspxhome.com/file/2023/4/123084_0s.jpg)
Dreamweaver制作网页11种技巧详解
2007-11-05 14:00:00
MYSQL SET类型字段的SQL操作知识介绍
2024-01-20 20:00:38
MySql COALESCE函数使用方法代码案例
2024-01-14 03:47:25
![](https://img.aspxhome.com/file/2023/5/75565_0s.png)
详解python中@的用法
2022-05-15 04:52:32
正则化DropPath/drop_path用法示例(Python实现)
2022-12-01 21:58:34
python3爬虫之入门基础和正则表达式
2023-04-11 12:48:02
![](https://img.aspxhome.com/file/2023/8/77568_0s.jpg)