Skip to main content
 首页 » 编程设计

python之列表理解语法错误中的嵌套 if/else 子句

2025年05月04日13yyy_WW

从以下列表理解开始:

new_list = [re.sub(r'replace_a', 'with__b', i) 
             if not re.findall(r'find_pattern', i, re.M) else  
            re.sub(r'replace_c', r'with__d', i) 
            for i in old_list] 

现在我想在 else 之后添加一个 if 条件,使用 re.sub() 替换另一个模式。我试过:

new_list = [re.sub(r'replace_a', 'with_b', i) 
             if not re.findall(r'find_pattern', i, re.M) else 
           (re.sub(r'replace_c', r'with_d', i) 
             if foo == re.match("pattern", foo)) 
           for i in old_list] 

试图找出使用列表理解的正确方法,但没有成功。

请您参考如下方法:

作为常规 for 循环,这将更容易阅读:

new_list = [] 
for i in old_list: 
    if not re.findall(r'find_pattern', i, re.M): 
        new_list.append(re.sub(r'replace_a', 'with_b', i)) 
    elif foo == re.match("pattern", foo): 
        new_list.append(re.sub(r'replace_c', r'with_d', i)) 
    # else: 
    #    i 

您的问题是条件表达式必须始终采用else 子句,因为无论条件是否为真,它都必须有一些值。但是,对于 if 语句,您可以省略 else。例如,上面的代码能够使 new_list 比 old_list 更短,因为不是每个 i 都需要调用 >new_list.append。取消注释 else 的结果与 jpp 的答案相同。

如果你坚持使用列表理解,那么你可以格式化它以使其更具可读性。考虑

new_list = [re.sub(r'replace_pattern_a', 'with_pattern_b', i) 
               if not re.findall(r'find_pattern', i, re.M) else  
            re.sub(r'replace_pattern_c', r'with_pattern_d', i)  
               if foo == re.match("pattern", foo) else 
            i 
            for i in old_list] 

虽然条件表达式并不是为这种嵌套而设计的。这在视觉上将可以添加到新列表的表达式与用于做出决定的条件分开,但我不是很喜欢。还有其他格式化方式可以做出不同的权衡,但 IMO 常规 for 循环更优越。


正如 jpp 提到的,另一种重构方法是定义一个生成器函数:

def foo(old_list): 
    for i in old_list: 
        if not re.findall(r'find_pattern', i, re.M): 
            yield re.sub(r'replace_a', 'with_b', i)) 
        elif foo == re.match("pattern", foo): 
            yield re.sub(r'replace_c', r'with_d', i)) 
        else: 
            yield i 
 
new_list = list(foo()) 

这也有其优点和缺点。 (我认为列举这些可能超出了这个答案的范围,但它确实介于单个列表理解和显式 for 循环的两个极端之间。它也最接近我想念的构造从我的 Perl 时代开始,do 语句类似于 lambda,它不接受任何参数,但可以包含任意语句。)