内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

Python中generator生成器和yield表達式的示例分析-創(chuàng)新互聯(lián)

這篇文章主要介紹了Python中generator生成器和yield表達式的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

在五常等地區(qū),都構建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務理念,為客戶提供網(wǎng)站制作、成都網(wǎng)站建設 網(wǎng)站設計制作按需策劃設計,公司網(wǎng)站建設,企業(yè)網(wǎng)站建設,品牌網(wǎng)站設計,網(wǎng)絡營銷推廣,成都外貿網(wǎng)站建設公司,五常網(wǎng)站建設費用合理。

1. Iterator與Iterable

首先明白兩點:

  • Iterator(迭代器)是可迭代對象;

  • 可迭代對象并不一定是Iterator;

比較常見的數(shù)據(jù)類型list、tuple、dict等都是可迭代的,屬于collections.Iterable類型;

迭代器不僅可迭代還可以被內置函數(shù)next調用,屬于collections.Iterator類型;

迭代器是特殊的可迭代對象,是可迭代對象的一個子集。

將要介紹的gererator(生成器)是types.GeneratorType類型,也是collections.Iterator類型。

也就是說生成器是迭代器,可被next調用,也可迭代。

三者的包含關系:(可迭代(迭代器(生成器)))

  • 迭代器:可用next()函數(shù)訪問的對象;

  • 生成器:生成器表達式和生成器函數(shù);

2. Python生成器

python有兩種類型的生成器:生成器表達式和生成器函數(shù)。

由于生成器可迭代并且是iterator,因此可以通過for和next進行遍歷。

2.1 生成器表達式

把列表生成式的[]改成()便得到生成器表達式。

>>> gen = (i + i for i in xrange(10))
>>> gen
<generator object <genexpr> at 0x0000000003A2DAB0>
>>> type(gen)
<type 'generator'>
>>> isinstance(gen, types.GeneratorType) and isinstance(gen, collections.Iterator) and isinstance(gen, collections.Iterable)
True
>>>

2.2 生成器函數(shù)

python函數(shù)定義中有關鍵字yield,該函數(shù)便是一個生成器函數(shù),函數(shù)調用返回的是一個generator.

def yield_func():
  for i in xrange(3):
    yield i
gen_func = yield_func()
for yield_val in gen_func:
  print yield_val

生成器函數(shù)每次執(zhí)行到y(tǒng)ield便會返回,但與普通函數(shù)不同的是yield返回時會保留當前函數(shù)的執(zhí)行狀態(tài),再次被調用時可以從中斷的地方繼續(xù)執(zhí)行。

2.3 next與send

通過for和next可以遍歷生成器,而send則可以用于向生成器函數(shù)發(fā)送消息。

def yield_func():
  for i in xrange(1, 3):
    x = yield i
    print 'yield_func',x
gen_func = yield_func()
print 'iter result: %d' % next(gen_func)
print 'iter result: %d' % gen_func.send(100)

結果:

iter result: 1
yield_func 100
iter result: 2

簡單分析一下執(zhí)行過程:

  • line_no 5 調用生成器函數(shù)yield_func得到函數(shù)生成器gen_func;

  • line_no 6 使用next調用gen_func,此時才真正的開始執(zhí)行yield_func定義的代碼;

  • line_no 3 執(zhí)行到y(tǒng)ield i,函數(shù)yield_func暫停執(zhí)行并返回當前i的值1.

  • line_no 6 next(gen_func)得到函數(shù)yield_func執(zhí)行到y(tǒng)ield i返回的值1,輸出結果iter result: 1;

  • line_no 7 執(zhí)行gen_func.send(100);

  • line_no 3 函數(shù)yield_func繼續(xù)執(zhí)行,并將調用者send的值100賦值給x;

  • line_no 4 輸出調用者send接收到的值;

  • line_no 3 執(zhí)行到y(tǒng)ield i,函數(shù)yield_func暫停執(zhí)行并返回當前i的值2.

  • line_no 7 執(zhí)行gen_func.send(100)得到函數(shù)yield_func運行到y(tǒng)ield i返回的值2,輸出結果iter result: 2;

如果在上面代碼后面再加一行:

print 'iter result: %d' % next(gen_func)

結果:

iter result: 1
yield_func 100
iter result: 2
yield_func None
File "G:\Cnblogs\Alpha Panda\Main.py", line 22, in <module>
  print 'iter result: %d' % next(gen_func)
StopIteration

yield_func只會產(chǎn)生2個yield,但是我們迭代調用了3次,會拋出異常StopIteration。

next和send均會觸發(fā)生成器函數(shù)的執(zhí)行,使用for遍歷生成器函數(shù)時不要用send。原因后面解釋。

2.4 生成器返回值

使用了yield的函數(shù)嚴格來講已經(jīng)不是一個函數(shù),而是一個生成器。因此函數(shù)中yield和return是不能同時出現(xiàn)的。

SyntaxError: 'return' with argument inside generator

生成器只能通過yield將每次調用的結果返回給調用者。

2.5 可迭代對象轉成迭代器

list、tuple、dict等可迭代但不是迭代器的對象可通過內置函數(shù)iter轉化為iterator,便可以通過next進行遍歷;

這樣的好處是可以統(tǒng)一使用next遍歷所有的可迭代對象;

tup = (1,2,3)
for ele in tup:
  print ele + ele

上面的代碼等價于:

tup_iterator = iter(tup)while True:
  try:
    ele = next(tup_iterator)
  except StopIteration:
    break
  print ele + ele

for循環(huán)使用next遍歷一個迭代器,混合使用send可能會導致混亂的遍歷流程。

其實到這里生成器相關的概念基本已經(jīng)介紹完成了,自己動手過一遍應該能弄明白了。為了更加深刻的體會生成器,下面我們在往前走一步。

3. range與xrange

在Python 2中這兩個比較常用,看一下兩者的區(qū)別:

  • range為一個內置函數(shù),xrange是一個類;

  • 前者返回一個list,后者返回一個可迭代對象;

  • 后者遍歷操作快于前者,且占用更少內存;

這里xrange有點類似于上面介紹的生成器表達式,雖然xrange返回的并不是生成器,但兩者均返回并不包含全部結果可迭代對象。

3.1 自定義xrange的Iterator版本

作為一個iterator:

The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:

iterator.__iter__()
Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

iterator.next()
Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.

下面我們自定義class my_xrange:

class my_xrange(object):
  def __init__(self, start, stop = None, step = 1):
    """ 僅僅為了演示,假設start, stop 和 step 均為正整數(shù) """
    self._start = 0 if stop is None else start
    self._stop = start if stop is None else stop
    self._step = step
    self._cur_val = self._start

  def __iter__(self):
    return self
  def next(self):
    if self._start <= self._cur_val < self._stop:
      cur_val = self._cur_val
      self._cur_val += self._step
      return cur_val
    raise StopIteration

測試結果:

import collections
myxrange = my_xrange(0, 10, 3)
res = []
for val in myxrange:
  res.append(val)
print res == range(0, 10, 3)   # True
print isinstance(myxrange, collections.Iterator)  # Trueprint isinstance(myxrange, types.GeneratorType)  # False

3.2 使用函數(shù)生成器

下面使用函數(shù)生成器定義一個generator版的xrange。

def xrange_func(start, stop, step = 1):
  """ 僅僅為了演示,假設start, stop 和 step 均為正整數(shù) """
  cur_val = start
  while start <= cur_val and cur_val < stop:
    yield cur_val
    cur_val += step
isinstance(myxrange, collections.Iterator) and isinstance(myxrange, types.GeneratorType) is True

上面兩個自定義xrange版本的例子,均說明生成器以及迭代器保留數(shù)列生成過程的狀態(tài),每次只計算一個值并返回。這樣只要占用很少的內存即可表示一個很大的序列。

4. 應用

不管是迭代器還是生成器,對于有大量有規(guī)律的數(shù)據(jù)產(chǎn)生并需要遍歷訪問的情景均適用,占用內存少而且遍歷的速度快。其中一個較為經(jīng)典的應用為斐波那契數(shù)列(Fibonacci sequence)。

這里以os.walk遍歷目錄為例來說明yield的應用。如果我們需要遍歷一個根目錄下的所有文件并根據(jù)需要進行增刪改查??赡軙龅较铝械膯栴}:

預先遍歷且緩存結果,但是目錄下文件可能很多,而且會動態(tài)改變;如果不緩存,多個地方可能會頻繁的需要訪問這一結果導致效率低下。

這時候可以使用yield定義一個生成器函數(shù)。

def get_all_dir_files(target_dir):
  for root, dirs, files in os.walk(target_dir):
    for file in files:
      file_path = os.path.join(root, file)
      yield os.path.realpath(file_path)
def file_factory(file):
  """ do something """
target_dir = './'
all_files = get_all_dir_files(target_dir)
for file in all_files:
  file_factory(file)

感謝你能夠認真閱讀完這篇文章,希望小編分享的“Python中generator生成器和yield表達式的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關知識等著你來學習!

文章標題:Python中generator生成器和yield表達式的示例分析-創(chuàng)新互聯(lián)
URL網(wǎng)址:http://www.rwnh.cn/article16/jdpgg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、微信公眾號ChatGPT、動態(tài)網(wǎng)站響應式網(wǎng)站、搜索引擎優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

手機網(wǎng)站建設
开平市| 太白县| 吉安县| 洱源县| 宜章县| 崇信县| 比如县| 玛沁县| 巴林右旗| 和政县| 汝州市| 长阳| 武功县| 门头沟区| 子洲县| 南充市| 射洪县| 新乐市| 延川县| 秦皇岛市| 丹巴县| 扶绥县| 怀远县| 驻马店市| 宝坻区| 寻乌县| 同心县| 鄂托克前旗| 那坡县| 西充县| 朝阳区| 司法| 临澧县| 海兴县| 宜丰县| 彭水| 大悟县| 宁蒗| 塔城市| 梓潼县| 尖扎县|