溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python基礎(chǔ)【生成式 | 迭代器 | 生成器】

發(fā)布時間:2020-07-17 07:54:15 來源:網(wǎng)絡(luò) 閱讀:204 作者:流域哈哈 欄目:編程語言

生成式

列表生成式

快速生成具有特定規(guī)律的列表

  • 普通寫法:
    even=[]
    for i in range(100):
    if i%2==0:
    even.append(i)

  • 列表生成式形式:
    even=[i for i in range(100) if i%2==0] ##生成0-99之間的偶數(shù)

集合生成式

快速生成具有特定規(guī)律的集合

  • 集合生成式形式:
    even={i for i in range(100) if i%2==0} ##生成0-99之間的偶數(shù)

    字典生成式

    快速生成具有特定規(guī)律的字典

  • 普通寫法:
    info={}
    for i in range(100):
    info['student'+str(i)]=random.randint(1,100)

  • 列表生成式形式:
    info={'student'+str(i):random.randint(1,100) for i in range(100)}

迭代器

迭代是訪問集合元素的一種方式。

  • 迭代器是一個可以記住遍歷的位置的對象。
  • 迭代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結(jié)束。
  • 迭代器只能往前不會后退。
  • 迭代器有兩個基本的方法:iter() 和 next()。
    iter()用于創(chuàng)建迭代器對象:
    字符串,列表或元組對象都可用于創(chuàng)建迭代器:

    代碼:

    f=iter('str')
    print(f)
    f=iter([1,2,3])
    print(f)
    f=iter((1,2,3))
    print(f)

    測試結(jié)果:

    Python基礎(chǔ)【生成式 | 迭代器 | 生成器】
    next(generator object),next()方法會返回迭代器的下一個結(jié)果

    代碼:

    f=iter('str') ##生成迭代器對象
    while True:
    try:
    print(next(f),end=' ') ##利用next()返回迭代返回的下一個結(jié)果
    except:
    exit() ##迭代超出范圍會拋出一個異常,捕捉后退出程序

    測試結(jié)果:

    Python基礎(chǔ)【生成式 | 迭代器 | 生成器】

生成器

  • 在 Python 中,使用了 yield 的函數(shù)被稱為生成器(generator)。
  • 跟普通函數(shù)不同的是,生成器是一個返回迭代器的函數(shù),只能用于迭代操作,更簡單點理解生成器就是一個迭代器。
  • 在調(diào)用生成器運行的過程中,每次遇到 yield 時函數(shù)會暫停并保存當(dāng)前所有的運行信息,返回 yield 的值, 并在下一次執(zhí)行 next() 方法時從當(dāng)前位置繼續(xù)運行。
  • 調(diào)用一個生成器函數(shù),返回的是一個迭代器對象。

創(chuàng)立生成器對象的兩種方法

方法一:

num=(x**2 for x in range(100))

此時num就是一個生成器對象

方法二:

import sys
def fibonacci(n): # 生成器函數(shù) - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一個迭代器,由生成器返回生成
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()

生成器應(yīng)用

利用生成器實現(xiàn)攜程(單線程并發(fā))

def add(a):
    while True:
        a=a+1
        yield a
def punc(a):
    b=1
    while True:
        b+=1
        a=a*b
        yield a
sum=add(1)
pro=punc(1)
while True:
    print(next(sum))
    print(pro.__next__())

利用send()與進(jìn)程進(jìn)行交互

def add(a):
    while True:
        a=a+1
        a=yield a
def punc(a):
    b=1
    while True:
        b+=1
        a=a*b
        a=yield a
sum=add(1)
pro=punc(1)
print(next(sum))
print(pro.__next__())
while True:
    print(sum.send(1))
    print(pro.send(1))
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI