浅谈python迭代器

yipeiwu_com6年前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的所有运算式等,有什么问题可以随时留言,小编会及时回复大家的。感谢朋友们对本站的支持!

相关文章

Pytorch中index_select() 函数的实现理解

函数形式: index_select( dim, index ) 参数: dim:表示从第几维挑选数据,类型为int值; index:表示从第一个参数维度中的哪个...

Python面向对象程序设计示例小结

本文实例讲述了Python面向对象程序设计。分享给大家供大家参考,具体如下: 示例1: #encoding:utf-8 '''example 1 class test: def...

python实现巡检系统(solaris)示例

使用python + shell 编写,是一个简易solaris系统巡检程序 复制代码 代码如下:#!/usr/bin/python -u#-*- coding:utf-8 -*-''...

跟老齐学Python之模块的加载

跟老齐学Python之模块的加载

不管是用import还是用from mmmm import *的方式导入模块,当程序运行之后,回头在看那个存储着mmmm.py文件的目录中(关于mmmm.py文件可以看上一讲),多了一个...

python 中文字符串的处理实现代码

>>> teststr = '我的eclipse不能正确的解码gbk码!' >>> teststr '\xe6\x88\x91\xe7\x9a\x84...