2017-10-16 54 views
-2

如何讓我的其他打印只打印一次,而不是每一行字符串不存在?我嘗試通過拖拽幾層來移動它,但它不起作用。我瞭解邏輯,但我不知道如何限制它。我一次添加一點點到我的練習解析腳本,隨着我的學習,但是這個幫助我。謝謝!打印其他只有一次?

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

在Python中,您可以在for循環中附加else子句。例如

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

5被發現,因此不執行else語句

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

documentation on for statements

的首套房執行break語句終止循環 不執行else子句的套件。在第一個套件中執行的繼續聲明 將跳過該套件的其餘部分,並在下一個項目中繼續使用 ,如果沒有下一個項目,則使用else子句繼續。

+2

什麼是有價值的信息。從來不知道這個! – Unni

+0

雷蒙德Hettinger建議'nobreak'關鍵字被介紹,但提案從來沒有通過...更多[這裏](https://www.youtube.com/watch?v=OSGv2VnC0go#t=17m12s) – mentalita

+0

@mentalita謝謝爲鏈接。我同意它在目前的實現中有點混亂 –

3

請先看吉布森的回答。你可以這樣做:

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!" 

您也可以省略found標誌(如讓·弗朗索瓦·法布爾建議在評論),但是這使得有點難以海事組織理解(我在我的頭上來編譯):

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