欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談python迭代器

 更新時間:2017年11月08日 08:51:09   作者:bloke  
這篇文章主要介紹了淺談python迭代器,具有一定參考價值,需要的朋友可以了解下。

1、yield,將函數(shù)變?yōu)?generator (生成器)

例如:斐波那契數(shù)列

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循環(huán)的對象,統(tǒng)稱為 Iterable (可迭代)

from collections import Iterable, Iterator
print(isinstance(fib(10), Iterable))
print(isinstance(range(10), Iterable))
# True
# True

3、Iterator

可以使用next() <__next__()> 函數(shù)調(diào)用并且不斷返回下一個值的對象成為 Iterator (迭代器),表示一個惰性計算的序列。

list, dict, str是Iterable,不是Iterator:

from collections import Iterator
print(isinstance(list(), Iterator))
# False

但是可以通過iter()函數(shù)將其變?yōu)镮terator:

print(isinstance(iter(list()), Iterator))
# True

總結(jié)

以上就是本文關(guān)于淺談python迭代器的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:python好玩的項目—色情圖片識別代碼分享、Python實(shí)現(xiàn)一個簡單的驗(yàn)證碼程序、Python算法輸出1-9數(shù)組形成的結(jié)果為100的所有運(yùn)算式等,有什么問題可以隨時留言,小編會及時回復(fù)大家的。感謝朋友們對本站的支持!

相關(guān)文章

最新評論