ホームページ  >  記事  >  バックエンド開発  >  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. 複数のシーケンスを同時に反復します

シナリオ: 複数を同時に反復したいシーケンスは一度に 1 つのシーケンスから 1 つの要素を取得します

解決策: zip() 関数を使用します

Python のイテレータとジェネレータのインスタンスの詳細な説明

Python のイテレータとジェネレータのインスタンスの詳細な説明

Python のイテレータとジェネレータのインスタンスの詳細な説明

Python のイテレータとジェネレータのインスタンスの詳細な説明

6. 異なるセットでの要素の反復

アプリケーションシナリオ: 複数のオブジェクトに対して同じ操作を実行したいが、これらのオブジェクトは異なるコンテナーにあります

解決策: itertool.chain() 関数を使用します

Python のイテレータとジェネレータのインスタンスの詳細な説明

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。