vue元件庫用markdown生成文件
阿新 • • 發佈:2020-07-22
迭代器:
1, 什麼是迭代器
器: 工具
迭代: 是一個重複的過程, 但是每次重複都是基於上一次的結果而來的
name = ["egon", "lqz", "tank"]
count = 1
while count < len(names):
print(nmes[count])
count += 1
迭代器: 就是一種不依賴索引的取值工具
2, 為何要有迭代器
特性:
1, 是一種通用的迭代取值方案
2, 惰性計算, 節省記憶體
3, 如何用迭代器
dic = {"name": "egon", 'age': 18, 'gender': "male"} dic_iterator = dic.__iter__() res1 = dic_iterator.__next__() print(res1) res2 = dic_iterator.__next__() print(res2) res = dic_iterator.__next__() print(res) dic_iterator.__next__() # StopIteration 丟擲異常 while True: try: res = dic_iterator.__next__() print(res) except StopIteration: # 解決丟擲異常 break
可迭代物件與迭代器物件
內建有__iter__方法的型別稱之為: 可迭代物件 / 型別
字典
集合
檔案物件(也是迭代器物件)
字串
列表
元祖
迭代器物件: 內建有__iter_, __next___方法
dic = {"name": "egon", 'age': 18, 'gender': "male"}
dic_iterator = dic.__iter__()
dic_iterator.__next__()
for工作迴圈原理
dic = {"name": "egon", 'age': 18, 'gender': "male"} dic_iterator = dic.__iter__() while True: try: res = dic_iterator.__next__() print(res) except StopIteration: break for k in dic: print(k)
步驟1
dic_iterator = dic.__iter__()
步驟2
k = dic_iterator.__next__(), 執行迴圈體程式碼
步驟3
迴圈往復,直到丟擲異常,for迴圈會幫我們捕捉異常結束迴圈
dic = {"name": "egon", 'age': 18, 'gender': "male"}
dic_iterator = dic.__iter__()
for k in dic_iterator:
print(k)
print(dic_iterator)
四:基於同一迭代器的重複取值,效果如何????
示例1:
dic = {"name": "egon", 'age': 18, 'gender': "male"}
dic_iterator = dic.__iter__()
while True:
try:
res = dic_iterator.__next__()
print(res)
except StopIteration:
break
while True:
try:
res = dic_iterator.__next__()
print(res)
except StopIteration:
break
示例2:
dic = {"name": "egon", 'age': 18, 'gender': "male"}
for k in dic: # dic.__iter__()
print(k)
for k in dic: # dic.__iter__()
print(k)
自定義迭代器來實現惰性計算, 從而達到節省記憶體的效果
生成器
什麼是生成器
但凡是函式內出現了yield關鍵字, 呼叫函式將不會執行函式體程式碼, 會得到一個返回值,
該返回值就是我們自定義的迭代器, 稱之為生成器
def func():
print("hello")
yield 1
print("hello")
yield 2
print("hello")
yield 3
g = func()
print(g) # 生成器本身就是一個迭代器
res = next(g)
print(res)
res = next(g)
print(res)
res = next(g)
print(res)
yield與return
相同點: 都可以用來返回值
不同點:
return只能返回一次值, 函式就立刻結束了
yield能返回多次值, yield可以掛起函式
案例
def func():
res = 0
while True:
res += 1
yield res
g = func()
for i in g:
print(i)
總結迭代器的優缺點
優點:
1, 是一種通用的迭代取值方案
2, 惰性計算, 節省記憶體
缺點:
1, 取值不如索引, key的取值方式靈活
2, 取值是一次性的, 只能往後取, 不能預估值得個數
案例:
def my_range(start, stop, step=1):
while start < stop:
yield start
start += stop
for i in my_range(1, 5, 2):
print(i)
生成式:
列表生成式
l = [i ** 2 for i in range(5) if i > 2]
print(l)
names = ['lqz_sb', 'yj_sb', 'jason_sb', 'egon']
l = [name for name in names if name.endswith("sb")]
print(l)
集合生成式
res = {i for i in range(3)}
print(res)
字典生成式
res = {f"k{i}": i ** 2 for i in range(5)}
print(res)
生成器表示式
res(i for i in range(5))
print(res, type(res))
nums = (i for i in range(200000))
res = sum(nums)
print(res)
with open("a.txt", mode='rt', encoding='utf-8')as f:
# data = f.read()
# print(len(data))
# res = 0
# for line in f:
# res += len(line)
# res = sum(len(line) for line in f)
res = sum(len(line) for line in f)
print(res)