Python有条件性的声明吗?



我想过滤一个值列表。根据变量的状态,我想返回过滤器的正或负结果。示例:

def foo(it, my_condition):
    return [s for s in it if (s.startswith("q") if my_condition else not s.startswith("q"))]
foo(["The", "quick", "brown", "fox"], my_condition=True)

所以在my_condition=True上我得到["quick"],在my_condition=False上我得到["The", "brown", "fox"]

我不喜欢实现的是:(s.startswith("q") if filter else not s.startswith("q"))。它包含重复的代码,并在原本简洁的列表理解中占用了很多空间。我真正想要的只是在if之后插入not,具体取决于filter变量的状态。

是否有更漂亮/干净的解决方案?如果可能的话,我想避免在这种情况下避免使用lambda表达式的计算开销。

只需将startswith的结果与布尔参数进行比较:

def foo(it, keep_matches):
    return [s for s in it if s.startswith("q") == keep_matches]

注意:不要调用您的变量filter,因为这是一个内置的函数以过滤迭代,我更改了一个更明确的名称(不确定它是最佳选择,但它比flagfilter更好>

最新更新