源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

浅谈python迭代器

  • 时间:2020-03-20 05:45 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:浅谈python迭代器
[b]1、yield,将函数变为 generator (生成器)[/b] 例如:斐波那契数列
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
[b]2、Iterable[/b] 所有可以使用for循环的对象,统称为 Iterable (可迭代)
from collections import Iterable, Iterator
print(isinstance(fib(10), Iterable))
print(isinstance(range(10), Iterable))
# True
# True
[b]3、Iterator[/b] 可以使用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
[b]总结[/b] 以上就是本文关于浅谈python迭代器的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:[url=http://www.1sucai.cn/article/127697.htm]python好玩的项目—色情图片识别代码分享[/url]、[url=http://www.1sucai.cn/article/127496.htm]Python实现一个简单的验证码程序[/url]、[url=http://www.1sucai.cn/article/127483.htm]Python算法输出1-9数组形成的结果为100的所有运算式[/url]等,有什么问题可以随时留言,小编会及时回复大家的。感谢朋友们对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部