1. 程式人生 > >Python學習——生成器&迭代器

Python學習——生成器&迭代器

>>> a=[x**2 for x in range(10)]
>>> a
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>

>>> def f(n):
...     return n**3
...
>>> a = [f(x) for x in range(10)]
>>> a
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
>>>

一種賦值的形式

t = (1,2)
a,b = t    #賦值的左右邊數目對等,不然會報錯

a=1
b=2

生成器 generator

>>> s=(x for x in range(10))
>>> s
<generator object <genexpr> at 0x003339B0>
>>>

#################################

>>> s=(x for x in range(10))
>>> s
<generator object <genexpr> at 0x008A3F30>
>>>
>>> x=[s]
>>> x
[<generator object <genexpr> at 0x008A3F30>]
>>>
>>> print(s.__next__())
0
>>> print(s.__next__())
1
>>> print(s.__next__())
2
>>> print(s.__next__())
3
>>>

 #正確的迭代方法

>>> print(next(s))
4
>>> print(next(s))
5
>>> print(next(s))
6
>>>

#迭代結束 StopIteration

For迴圈 迭代

>>> s=(x for x in range(100))
>>> for i in s:
...     print(i)
...
0
1
2
3
4
5
6
7
8

生成器的建立方式

1、(x for x in range(10)) 2、通過yield

>>>
>>> def foo():
...     yield 1
...
>>> print(foo)
<function foo at 0x007F07C8>
>>> g=foo()
>>> g
<generator object foo at 0x00823F30>


########################################
def foo():
    print("step01")
    yield 1
    print("step02")
    yield 2
        
g=foo()
print(g)
print(next(g))
print(next(g))

<generator object foo at 0x014F3F30>
step01
1
step02
2

########################################
def foo():
	print("step01")
	yield 1
	print("step02")
	yield 2

#g=foo()
#print(g)
#print(next(g))
#print(next(g))

print(next(foo()))
print(next(foo()))

step01
1
step01
1
    
########################################

def foo():
	print("step01")
	yield 1
	print("step02")
	yield 2

#for迴圈遍歷可迭代物件
for x in foo():
	print(x)

可迭代物件: 內部有 __iter__() 方法的就是可迭代物件 字串 (str)–> 迭代器 列表(list)–> 迭代器 元組(tuple)–> 迭代器 字典(dictionary)–> 迭代器 range物件 --> 迭代器

生成器 就是 迭代器

斐波拉契數列

def fib(max):
	n,a,b=0,0,1
	while n<max:
		#print(a)
		yield a
		#先計算右邊 a 和 (a+b)的值			
		#相當於 a,b=0,(0+1)
		a,b=b,a+b 
		n+=1

for i in fib(5):
	print(i)

send() 方法

def foo():
	print("step01")
	var = yield 1
	print("step02,var is",var)
	var = yield 2
	print("step03,var is",var)
	yield 3



b=foo()
# 第一次send前沒有資料,只能send None 相當於next(b)
# TypeError: can't send non-None value to a just-started generator
print(b.send(None))
print(b.send("send msg01"))
print(b.send("send msg02"))

--------------------------------------------------------------------------------------------
step01
1
step02,var is send msg01
2
step03,var is send msg02
3

生成器和迭代器的關係:生成器都是迭代器

# 返回迭代器物件
b = a.__iter__()
b = iter(a)
# a可以為:str,list,tuple,dict,range 等可迭代物件

可迭代物件滿足:有 __iter__() 方法 迭代器滿足:有 __next()__ 方法

>>> s = (x for x in range(10))
>>> s
<generator object <genexpr> at 0x03613F30>
>>> a = iter(s)
>>> a
<generator object <genexpr> at 0x03613F30>
>>> a = s.__iter__()
>>> a
<generator object <genexpr> at 0x03613F30>
>>> type(a)
    <class 'generator'>

# 生成器 既是可迭代物件 又是 迭代器
>>> print(isinstance(s,Iterator))
True
>>> print(isinstance(s,Iterable))
True

在這裡插入圖片描述