day13-生成器

def generator():
    print(1)
    yield 'a'
rcp = generator()
print(rcp.__next__())

  只要含有yield關鍵字的函數都是生成器函數。yield不能和return共用且須要寫在函數內。函數

  生成器函數 : 執行以後會獲得一個生成器做爲返回值。spa

def generator():
    print(1)
    yield 'a'
    print(2)
    yield 'b'
rcp = generator()
put = rcp.__next__()
print(put)
put = rcp.__next__()
print(put)

  yield沒有結束一個函數,能夠連續打印。code

# 產生200個字符串def putStr():    for i in range(200):        yield '我最帥%d'%iput = putStr()for i in put:    print(i)

# 可不能夠在兩百個字符串中只取五十個,而後再緊接着上一次結束的地方再取五十個呢?def putStr():    for i in range(200):        yield '你最帥%s'%iput = putStr()count = 0for i in put:    print(i)    count += 1    if count >= 50:        breakprint('----------------------')for i in put:    print(i)    count += 1    if count >= 100:        break

  生成器能夠生成n個你想要的字符串。blog

# 監聽文件輸入
def func(filename):
    f = open(filename,encoding='utf-8')
    while True:
        line = f.readline()
        if line.strip():
            yield line
g = func('file')
for i in g:
    print(i)

  一個利用監聽器實現的監聽文件輸入操做。ip

相關文章
相關標籤/搜索