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

高洛峰
リリース: 2017-03-31 09:45:18
オリジナル
1692 人が閲覧しました

この記事では、主に 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. エージェントの反復

アプリケーション シナリオ: list 、タプル、または他の反復​​可能なオブジェクト

解決策: 反復操作をコンテナー内のオブジェクトにプロキシするための 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 <p style="text-align: left;">4. 選択的反復</p><p style="text-align: left;"><strong>アプリケーション シナリオ:反復可能なオブジェクトですが、先頭の一部の要素には興味がないのでスキップしたいです </strong></p>解決策: itertools.dropwhile() を使用します<p style="text-align: left;"></p>例 1<p style="text-align: left;"></p><pre class="brush:php;toolbar:false">with open('/etc/passwd') as f:
  for line in f:
    print(line,end='')
ログイン後にコピー
例 2

from itertools import dropwhile
with open('/etc/passwd') as f:
  for line in dropwhile(lambda line:line.startwith('#'),f):
    print(line,end='')
ログイン後にコピー

5 で複数のシーケンスを繰り返します。同時に

アプリケーションシナリオ: 複数のシーケンスを同時に繰り返し、毎回各シーケンスから 1 つの要素を取得したい

解決策:

zip

() 関数を使用します

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

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

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

Python のイテレータとジェネレータのインスタンス メソッドの詳細な説明6. 異なるコレクション上の要素の反復

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

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

Python のイテレータとジェネレータのインスタンス メソッドの詳細な説明7. ネストされたシーケンスを展開する

アプリケーションシナリオ: 複数レベルのネストされたシーケンスを単一レベルのリストに展開したい

解決策: yield from ステートメントを使用する

Recursive

Generator

Example

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

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!