2014-11-20 69 views
0

我對python和一般編程非常新。我試圖將文件中的單詞匹配到列表中的任何一個項目,並且一旦匹配被發現返回true。即使使用中斷匹配,我的代碼在第一場比賽中也不會中斷。 請原諒任何明顯的錯誤和錯誤的編碼風格。與任何列表項匹配並打破第一場比賽

strings = ["string1", "string2", "string3", "string4"] 
node_file = open(filename, 'r') 

##printing to check for first match 
for line in node_file: 
    words = line.split(" ") 
    for w in words: 
     for string in strings: 
      if re.match(string,w): 
       print 'found match' , w 
       break 
+1

考慮使用'in'函數列出例如'if w in strings' – user2097159 2014-11-20 19:17:12

+0

謝謝。我現在做了。 – newbie263 2014-11-20 19:41:21

回答

0

break只適用於它在其中執行的最內層循環;如果你想突破任何一個封閉循環,你需要一些額外的機制。例如,要突破所有的其中,你可以把它放在函數&使用return來退出函數。另一種方法是設置一些變量,比如說done,當你想要中斷的時候它會被設置,並且每個循環都會檢查它是否需要中斷。

+0

謝謝!把它放在一個函數中,現在就可以工作 – newbie263 2014-11-20 19:42:12

相關問題