2012-11-12 99 views
10

Python中是否有與unless語句等效的語句?我不想一行附加到一個標籤,如果它有它p4port除非Python中的語句

for line in newLines: 
    if 'SU' in line or 'AU' in line or 'VU' in line or 'rf' in line and line.find('/*') == -1: 
     lineMatch = False 
    for l in oldLines: 
     if '@' in line and line == l and 'p4port' not in line: 
      lineMatch = True 
      line = line.strip('\n') 
      line = line.split('@')[1] 
      line = line + '<br>\n' 
      labels.append(line) 
    if '@' in line and not lineMatch: 
     line = line.strip('\n') 
     line = line.split('@')[1] 
     line="<font color='black' style='background:rgb(255, 215, 0)'>"+line+"</font><br>\n" 
     labels.append(line) 

我得到一個語法錯誤:

if '@' in line and not lineMatch: 
    UnboundLocalError: local variable 'lineMatch' referenced before assignment 

回答

17

什麼「不」?:

if 'p4port' not in line: 
    labels.append(line) 

此外,我猜你的代碼可以再修改爲:

if '@' in line and line == l and 'p4port' not in line: 
    lineMatch = True 
    labels.append(line.strip('\n').split('@')[1] + '<br>\n') 
5

有沒有「除非」的聲明,但你總是可以寫:

爲Artsiom提到
if not some_condition: 
    # do something 

還有就是在not in運營商 - 所以你的代碼,你會寫:

if '@' in line and line == l: 
    lineMatch = True 
    line = line.strip('\n') 
    line = line.split('@')[1] 
    line = line + '<br>\n' 
    if 'p4port' not in line: 
     labels.append(line) 

..但Artsiom的版本更好,除非你打算在以後修改line變量。

+0

如何修改我當前的if語句來執行「if not in p4port」並且不擾亂當前的邏輯 – user1795998

1

您在編輯的問題中遇到的錯誤是告訴您變量lineMatch不存在 - 這意味着您指定的設置條件未滿足。這可能有助於在外部for循環內(在第一個if聲明之前)添加一行,如LineMatch = False作爲第一行,以確保它確實存在。