脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 浅谈python迭代器

浅谈python迭代器

2020-12-16 00:32bloke Python

这篇文章主要介绍了浅谈python迭代器,具有一定参考价值,需要的朋友可以了解下。

1、yield,将函数变为 generator (生成器)

例如:斐波那契数列

?
1
2
3
4
5
6
7
8
9
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 (可迭代)

?
1
2
3
4
5
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:

?
1
2
3
from collections import Iterator
print(isinstance(list(), Iterator))
# False

但是可以通过iter()函数将其变为Iterator:

?
1
2
print(isinstance(iter(list()), Iterator))
# True

总结

以上就是本文关于浅谈python迭代器的全部内容,希望对大家有所帮助。有什么问题可以随时留言,小编会及时回复大家的。感谢朋友们对本站的支持!

原文链接:http://www.cnblogs.com/bloke/p/7801480.html

延伸 · 阅读

精彩推荐