在 Python 中压缩 `x if x else y` 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14105500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compressing `x if x else y` statement in Python
提问by Rubens
I'm quite acquainted with Python's ternary operator approach:
我非常熟悉 Python 的三元运算符方法:
value = foo if something else bar
My question is very simple: without prior assignments, is there anyway to reference the term being evaluated in (if ...) from one of the return operands (... ifor else ...)?
我的问题很简单:在没有事先赋值的情况下,是否可以if ...从返回操作数之一 ( ... ifor else ...) 中引用 ( ) 中正在评估的术语?
The motivation here is that sometimes I use expressions in if ...that are exactly what I'd like to have as result in the ternary operation; happens though that, for small expressions, there's no problem repeating it, but for a bit longer expressions, it goes somewhat nasty. Take this as an example:
这里的动机是有时我使用的表达式if ...正是我想要在三元运算中得到的结果;尽管如此,对于小的表达式,重复它没有问题,但是对于更长的表达式,它有点令人讨厌。以此为例:
value = info.findNext("b") if info.findNext("b") else "Oompa Loompa"
采纳答案by abarnert
There is no way to do this, and that's intentional. The ternary if is only supposed to be used for trivial cases.
没有办法做到这一点,这是故意的。三元 if 只应该用于琐碎的情况。
If you want to use the result of a computation twice, put it in a temporary variable:
如果要两次使用计算结果,请将其放入临时变量中:
value = info.findNext("b")
value = value if value else "Oompa Loompa"
Once you do this, it becomes clear that you're doing something silly, and in fact the pythonic way to write this is:
一旦你这样做,很明显你在做一些愚蠢的事情,实际上写这个的pythonic方式是:
value = info.findNext("b")
if not value:
value = "Oompa Loompa"
And that's actually 5 fewerkeystrokes than your original attempt.
这实际上比您最初的尝试少了5次击键。
If you reallywant to save keystrokes, you can instead do this:
如果你真的想保存击键,你可以这样做:
value = info.findNext("b") or "Oompa Loompa"
But that's discouraged by many style guides, and by the BDFL.
但许多风格指南和 BDFL 都不鼓励这样做。
If you're only doing this once, it's better to be more explicit. If you're doing it half a dozen times, it's trivial—and much better—to make findNexttake an optional default to return instead of None, just like all those built-in and stdlib functions:
如果你只这样做一次,最好更明确。如果您执行了六次,那么就像所有这些内置函数和 stdlib 函数一样,findNext使用可选的默认值来 return 而不是,这是微不足道的——而且要好得多None:
def findNext(self, needle, defvalue=None):
# same code as before, but instead of return None or falling off the end,
# just return defvalue.
Then you can do this:
然后你可以这样做:
value = info.findNext("b", "Oompa Loompa")
回答by Ignacio Vazquez-Abrams
Don't use if ... elseat all. Instead, take advantage of Python's coalescing operators.
根本不要用if ... else。相反,请利用 Python 的合并运算符。
value = info.findNext("b") or "Oompa Loompa"

