首頁  >  文章  >  後端開發  >  Python中迭代器與生成器實例詳解

Python中迭代器與生成器實例詳解

Y2J
Y2J原創
2017-04-20 09:58:511334瀏覽

這篇文章主要介紹了Python 中迭代器與生成器實例詳解的相關資料,需要的朋友可以參考下

Python 中迭代器與生成器實例詳解

#本文透過針對不同應用場景及其解決方案的方式,總結了Python中迭代器與生成器的一些相關知識,具體如下:

1.手動遍歷迭代器

應用場景:想遍歷一個可迭代物件中的所有元素,但是不想用for迴圈

解決方案:使用next()函數,並捕獲StopIteration異常


def manual_iter():
  with open('/etc/passwd') as f:
    try:
      while True:
        line=next(f)
        if line is None:
          break
        print(line,end='')
      except StopIteration:
        pass


#test case
items=[1,2,3]
it=iter(items)
next(it)
next(it)
next(it)

2.代理程式迭代

##應用場景:想直接在一個包含有列表、元組或其他可迭代物件的容器物件上執行迭代操作


解決方案:定義一個iter()方法,將迭代操作代理到容器內部的物件上

範例:



class Node:
  def init(self,value):
    self._value=value
    self._children=[]
  def repr(self):
    return 'Node({!r})'.fromat(self._value)
  def add_child(self,node):
    self._children.append(node)
  def iter(self):
    #将迭代请求传递给内部的_children属性
    return iter(self._children)


#test case
if name='main':
  root=Node(0)
  child1=Node(1)
  child2=Nide(2)
  root.add_child(child1)
  root.add_child(child2)
  for ch in root:
    print(ch)

3.反向迭代

應用程式場景:想要反向迭代一個序列


解決方案:使用內建的reversed()函數或在自訂類別上實作reversed()

範例1



a=[1,2,3,4]
for x in reversed(a):
  print(x) #4 3 2 1


f=open('somefile')
for line in reversed(list(f)):
  print(line,end='')
#test case
for rr in reversed(Countdown(30)):
  print(rr)

for rr in Countdown(30):
  print(rr)

範例2



class Countdown:
  def init(self,start):
    self.start=start
  #常规迭代
  def iter(self):
    n=self.start
    while n > 0:
      yield n
      n -= 1
  #反向迭代
  def reversed(self):
    n=1
    while n <= self.start:
      yield n
      n +=1

##4 .有選擇的迭代


應用場景:想遍歷一個可迭代對象,但是對它開始的某些元素並不感興趣,想跳過


#解決方案:使用itertools.dropwhile()

範例1


with open(&#39;/etc/passwd&#39;) as f:
  for line in f:
    print(line,end=&#39;&#39;)

範例2





##
from itertools import dropwhile
with open(&#39;/etc/passwd&#39;) as f:
  for line in dropwhile(lambda line:line.startwith(&#39;#&#39;),f):
    print(line,end=&#39;&#39;)

5.同時迭代多個序列

Python中迭代器與生成器實例詳解

應用場景:想同時迭代多個序列每次分別從一個序列中取一個元素Python中迭代器與生成器實例詳解

解決方案:使用zip()函數Python中迭代器與生成器實例詳解

Python中迭代器與生成器實例詳解



6.不同集合上元素的迭代

Python中迭代器與生成器實例詳解

應用場景:想在多個物件執行相同的操作,但是這些物件在不同的容器中
解決方案:使用itertool.chain()函數


7.展開巢狀的序列


應用程式場景:想將一個多層巢狀的序列展開成一個單層清單

#解決方案:使用包含yield from語句的遞迴產生器

範例###############
from collections import Iterable
def flatten(items,ignore_types=(str,bytes)):
  for x in items:
    if isinstance(x,Iterable) and not isinstance(x,ignore_types):
      yield from flatten(x)
    else:
      yield x
#########
#test case
items=[1,2,[3,4,[5,6],7],8]
for x in flatten(items):
  print(x)

以上是Python中迭代器與生成器實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn