2017-10-20 6 views
1

ネストループを実行しているコードがあります。私はこれを行うためのより "ピジョン"の方法があると推測しています。助言がありますか?Pythonでネストされたループを反復処理するより良い方法はありますか?

コードの基本的な部分は次のようになります。

for e in range(len(listOfTuples)): 

     for item in self.items: 
      if item.getName() == listOfTuples[e][0]: 
       <do stuff> 
      if item.getName() == listOfTyples[e][1]: 
       <do other stuff> 
       continue 

     if <both above if statements got answers>: 
      <do yet more stuff> 

は、これらのネストされたループを書くための良い方法はありますか?

+0

'if'の代わりに' elif'を使うことができます –

+0

@Jean 'if'sは相互排他的ではありません。 – Blorgbeard

+1

インデックスが必要なようには見えないので、listOfTuplesの 'for for tuple:'を実行することができます: '(浅い)ネストされたループについては、何もpyononicがありません。 – Blorgbeard

答えて

0

ジェネレータ機能を使用できます。少なくとも、それはネストされたforループの "醜さ"を隠します。

def combine_items_and_tuples(items, listOfTuples): 
    for e in range(len(listOfTuples)): 
     for item in items: 
      yield e, item 

単純にそれを呼び出す:それは反復可能であるので、あなたはまた、直接listOfTuplesの反復処理することができ、すでにコメントで述べた

for e, item in combine_items_and_tuples(self.items, listOfTuples): 
     if item.getName() == listOfTuples[e][0]: 
       <do stuff> 
     if item.getName() == listOfTyples[e][1]: 
       <do other stuff> 
       continue 

     if <both above if statements got answers>: 
      <do yet more stuff> 

(パイソンglossaryで見て):

listOfTuplesオーバー直接
for tuple in listOfTuples: 
0

反復と

について我々は気に値を展開0
for a, b, *_ in listOfTuples: 

    a_check, b_check = False, False 

    for item in self.items: 
     if item.name == a: 
      #do stuff 
      a_check = True   
     if item.name == b: 
      #do stuff 
      b_check = True 

    if a_check and b_check: 
     #do more stuff 

*_は、(私たちが望むすべては最初の2つの要素であると仮定)listOfTuples中のタプルの最初の2つの要素を過ぎてのものをキャプチャします。

通知item.getNameの代わりにitem.nameを使用します。 Pythonは一般的にgetterとsetterを気にしません。なぜなら、private変数の実際の概念がないからです。

関連する問題