for in
語法,問個問題那麼 for in
是怎麼知道自己要跑幾次呢?arr = [1, 2]
for i in arr:
print(i) # 1 2 3
for in
實際上是呼叫 arr
裡面的 __iter__()
方法並取得一個 iterator
物件,然後每次再通過 iterator
物件中的 __next__()
方法不斷取得值,直到跑出 StopIteration
的例外。arr = [1, 2]
iterator = arr.__iter__()
i = iterator.__next__()
print(i) # 1
i = iterator.__next__()
print(i) # 2
i = iterator.__next__() # StopIteration
print(i)
1
2
Traceback (most recent call last):
File "test.py", line 7, in <module>
i = iterator.__next__()
StopIteration
遍歷
,Iterator 被遍歷過一次之後就無法再次被遍歷arr = [1, 2]
iterator = arr.__iter__()
for i in iterator:
print(i)
for i in iterator:
print(i)
1 2
而不是兩次1
2
for i in iterator
也只是幫你 __next__()
,這樣我們就可以很粗淺的理解 Iterator 的概念了。–
from sys import getsizeof
arr = [i for i in range(100000)]
print(getsizeof(arr), " Bytes") # 824464 Bytes
gen = (i for i in range(100000))
print(getsizeof(gen), " Bytes") # 120 Bytes
from sys import getsizeof
arr = [i for i in range(100000)]
print(arr.__len__()) # 100000
gen = (i for i in range(100000))
print(gen.__len__()) # AttributeError: 'generator' object has no attribute '__len__'
yield
關鍵字,yield 關鍵字 可以理解為可以 return 值但不會中斷 function 的關鍵字。def getSomething(n):
print("getSomething START")
arr = []
for i in range(0, n):
print("some ", i)
arr.append(i)
yield arr[len(arr) - 1]
print("getSomething END")
return arr
something = getSomething(3)
print(type(something))
getSomething START
some 0
some 1
some 2
getSomething END
<<class 'list'>>
getSomething START
都不會拿到<class 'generator'>
i = something.__next__()
然後把 i 印出def getSomething(n):
print("getSomething START")
arr = []
for i in range(0, n):
print("some ", i)
arr.append(i)
yield arr[len(arr) - 1]
print("getSomething END")
return arr
something = getSomething(3)
print(type(something))
i = something.__next__()
print(i)
<class 'generator'>
getSomething START
some 0
0
something.__next__()
之後 getSomething
這個方法才會第一次執行,那之後就跟 Iterator 差不多了 __next__()
到不能往下就會拋出 StopIteration
def getSomething(n):
print("getSomething START")
arr = []
for i in range(0, n):
print("some ", i)
arr.append(i)
yield arr[len(arr) - 1]
print("getSomething END")
return arr
something = getSomething(3)
print(type(something))
i = something.__next__()
print(i)
i = something.__next__()
print(i)
i = something.__next__()
print(i)
i = something.__next__() # StopIteration
print(i)
def getSomething(n):
arr = []
for i in range(0, n):
arr.append(i)
yield arr[len(arr) - 1]
return arr
for i in something:
print(i)
for i in something:
print(i)
1 2 3
而不是兩次1
2
3