浅谈python迭代器

yipeiwu_com5年前Python基础

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

总结

以上就是本文关于浅谈python迭代器的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:python好玩的项目—色情图片识别代码分享Python实现一个简单的验证码程序Python算法输出1-9数组形成的结果为100的所有运算式等,有什么问题可以随时留言,小编会及时回复大家的。感谢朋友们对本站的支持!

相关文章

在matplotlib的图中设置中文标签的方法

在matplotlib的图中设置中文标签的方法

其实就是通过 FontProperties来设置的,请参考以下代码: import matplotlib.pyplot as plt from matplotlib.font_man...

基于python实现文件加密功能

基于python实现文件加密功能

这篇文章主要介绍了基于python实现文件加密功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 生活中,有时候我们需要对一些重要的文...

浅谈django的render函数的参数问题

hello.html 文件代码如下: HelloWorld/templates/hello.html 文件代码: <h1>{{ hello }}</h1>...

django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决

django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决

一、现象 最近在数据库中删除了一张表,重新执行python manage.py migrate时出错,提示不存在这张表。通过查找相关的资料,最后找到了相关的解决方法,下面话不多说了,来一...

python实现邮件自动发送

本文实例为大家分享了python实现邮件自动发送的具体代码,供大家参考,具体内容如下 case 1:纯文本和HTML文件发送 # -*- coding: UTF-8 -*- im...