gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:09 26 4
gpt4 key购买 nike

从以下列表理解开始:

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_listold_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,它不接受任何参数,但可以包含任意语句。)

关于python - 列表理解语法错误中的嵌套 if/else 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49558561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com