网络编程
位置:首页>> 网络编程>> Python编程>> 浅谈python迭代器

浅谈python迭代器

作者:bloke  发布时间:2023-07-21 21:56:47 

标签: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

来源:http://www.cnblogs.com/bloke/p/7801480.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com