2017-10-16 15 views
-2

文字列が存在しない行ごとではなく、1回だけ印刷するようにelse印刷を行うにはどうすればよいですか?私はいくつかのレイヤーをタブで後ろに移動しようとしましたが、うまくいきません。私は論理を理解していますが、それをどのように制限するかはわかりません。私は練習用のスクリプトを解析するために一度に少しずつ追加していきます。ありがとう! Pythonでもう一度印刷しますか?

import csv 
# Testing finding something specifical in a CSV, with and else 
testpath = 'C:\Users\Devin\Downloads\users.csv' 
developer = "devin" 

with open (testpath, 'r') as testf: 
    testr = csv.reader(testf) 
    for row in testr: 
     for field in row: 
      if developer in row: 
       print row 
     else: 
      print developer + " does not exist!" 
+0

コード内に「開発者がいる場合:」とする必要がありますか? ( 'in row:'ではなく)? –

答えて

5

、あなたのforループに取り付けたelse句を持つことができます。 else文が最初のスイート内で実行break文を実行せずにループ を終了documentation on for statements

を参照してください

>>> for i in range(10): 
...  if i == 15: break 
... else: 
...  print 'not found' 
... 
not found 

実行されませんので、例えば

>>> for i in range(10): 
...  if i == 5: break # this causes the else statement to be skipped 
... else: 
...  print 'not found' 
... 

5が見つかりました。 else節のスイート。 continueステートメント は、最初のスイートで実行され、スイートの残りの部分をスキップし、次の項目には を続行します。次の項目がない場合はelse節で続きます。

+2

貴重な情報です。決してこれを知らなかった! – Unni

+0

Raymond Hettingerは、「nobreak」というキーワードを導入することを提案しましたが、提案は決して通過しませんでした... more [here](https://www.youtube.com/watch?v=OSGv2VnC0go#t=17m12s) – mentalita

+0

@mentalitaありがとうリンクのために。私はそれが現在の実装では少し混乱していることに同意します –

3

ギブソンの答えを最初に見てください。私は私の頭の中でコンパイルする必要がありました((コメントでジャン=フランソワ・ファーブルにより示唆されるように)またfoundフラグを省略することができますが、これは芋理解することは少し難しい可能

for row in testr: 
    found = False 
    for field in row: 
     if developer in row: 
      print row 
      found = True 
      break 
    if found: break 
else: 
    print developer + " does not exist!" 

:あなたはこれを行うことができます):

for row in testr:  
    for field in row: 
     if developer in row: 
      print row 
      # We found the developer. break from the inner loop. 
      break 
    else: 
     # This means, the inner loop ran fully, developer was not found. 
     # But, we have other rows; we need to find more. 
     continue 
    # This means, the else part of the inner loop did not execute. 
    # And that indicates, developer was found. break from the outer loop. 
    break 
else: 
    # The outer loop ran fully and was not broken 
    # This means, developer was not found. 
    print developer, "does not exist!" 
+0

'found'フラグは有用ではありません。内側のループでも 'else'トリックを使うことができます。 –

+0

真。回答が更新されました。ありがとう。 – mshsayem

関連する問題