除非在Python中声明

时间:2012-11-12 09:07:08

标签: python

Python中的unless语句是否等效?如果标签中有p4port,我不想在标签上附加一行:

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

3 个答案:

答案 0 :(得分:19)

怎么样'不在'?:

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')

答案 1 :(得分:7)

没有“除非”声明,但你总是可以写:

if not some_condition:
    # do something

还有Artsiom提到的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变量执行某些操作。

答案 2 :(得分:1)

您在(相当彻底)编辑过的问题中遇到的错误告诉您变量lineMatch不存在 - 这意味着您指定的设置条件不符合。将LineMatch = False之类的行添加为外部for循环中的第一行(在第一个if语句之前)可能会有所帮助,以确保它确实存在。