Python之生成器(yield)

2021-10-08 20:58:25 字數 3611 閱讀 7214

這裡是一段防爬蟲文字,請讀者忽略。

本文原創首發於csdn,作者idys

部落格首頁:

生成器函式

迭代器一定是可迭代物件,可迭代物件不一定是迭代器

def

inc():

for i in

range(5

):yield i

print

(type

(inc)

)print

(type

(inc())

)x = inc(

)print

(type

(x))

print

(next

(x))

for m in x:

print

(m, end=

"* "

)for m in x:

print

(m,"**"

)

<

class

'function'

>

<

class

'generator'

>

<

class

'generator'

>01

*2*3

*4*

my_func =

(i for i in

range(10

))print

(type

(my_func)

)print

(next

(my_func)

)print

(next

(my_func)

)

<

class

'generator'

>

01

def

gen():

print

("1"

)yield

1print

("2"

)yield

2print

("3"

)return

3print

(next

(gen())

)print

(next

(gen())

)g = gen(

)print

("***********************************"

)print

(next

(g))

print

(next

(g))

# print(next(g)) # 會報stopiteration 錯誤

print

(next

(g,"end"

))

111

1******

****

****

****

****

****

****

*****1

1223

end

deffn(

):i =

0while

true

: i = i +

1yield i

definc

(c):

return

next

(c)def

inc_two()

: c = fn(

)return

next

(c)c = fn(

)print

(inc(c)

)print

(inc(c)

)print

(inc_two())

# 顯示1

print

(inc_two())

# 顯示1

print

(inc_two())

# 顯示1

121

11

def

fib():

x =0 y =

1while

true

:yield y

y, x = x+y, y

foo = fib(

)for _ in

range(10

):print

(next

(foo)

, end=

" ")

112

35813

2134

55

協程是一種非搶占式排程

def

inc():

for x in

range

(1000):

yield x

definc_two()

:yield

from

range

(1000

)foo = inc(

)foo1 = inc_two(

)print

(next

(foo)

)print

(next

(foo)

)print

(next

(foo)

)print

("***************************"

)print

(next

(foo1)

)print

(next

(foo1)

)print

(next

(foo1)

)

012

****

****

****

****

****

*******

012

演示**

def

counter

(n):

for x in

range

(n):

yield x

definc

(n):

yield

from counter(n)

foo1 = inc(10)

print

(next

(foo1)

)print

(next

(foo1)

)print

(next

(foo1)

)print

(next

(foo1)

)

012

3

python中生成器yield

def yield demo for x in range 3 yield x print 生成器後一行 a yield demo print a 這裡的a是乙個生成器物件 可以用for迴圈來遍歷生成器物件裡的元素 for i in a print i 那麼yield的工作過程是怎麼樣的呢?可以通過...

Python生成器 yield的使用

通過列表生成式,我們可以直接建立乙個列表。但是,受到記憶體限制,列表容量肯定是有限的。而且,建立乙個包含100萬個元素的列表,不僅占用很大的儲存空間,如果我們僅僅需要訪問前面幾個元素,那後面絕大多數元素占用的空間都白白浪費了。所以,如果列表元素可以按照某種演算法推算出來,那我們是否可以在迴圈的過程中...

Python探險 生成器yield剖析

日期 20170926 本次執行環境python3 我們先來看一下 usr bin python3 defmygenerator yield 1yield 2yield 3return done print mygenerator print num mygenerator print num pr...