'... if ... else ...' 表达式的 Python 习语
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2529536/
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
Python idiom for '... if ... else ...' expression
提问by rukeba
How to write the expression shorter:
如何将表达式写得更短:
return '%.0f' % float_var if float_var else float_var
or
或者
if float_var:
return formatted_string
else:
return None
Thanks!
谢谢!
回答by John Feminella
The expression <value> if <condition> else <other_value>
is pretty idiomatic already -- certainly more so than the other example, and is probably preferred whenever <value>
is simple. This is Python's ternary operator, so if you were looking for something like <condition> ? <value> : <other_value>
, that doesn't exist.
这个表达式<value> if <condition> else <other_value>
已经非常惯用了——当然比另一个例子更惯用,并且在<value>
简单的时候可能是首选。这是 Python 的三元运算符,因此如果您正在寻找类似 的东西<condition> ? <value> : <other_value>
,那么它不存在。
If computing <value>
or <other_value>
takes a few steps, use the longer if: ... else: ...
alternative.
如果计算<value>
或<other_value>
需要几个步骤,请使用更长的if: ... else: ...
替代方案。
回答by Dave Kirby
I would use brackets to make the expression more readable:
我会使用括号使表达式更具可读性:
return ('%.0f' % float_var) if float_var else float_var
When I first saw it I read it as
当我第一次看到它时,我把它读为
return '%.0f' % (float_var if float_var else float_var)
which would be silly. I had to try it out to make sure which way it worked.
这将是愚蠢的。我不得不尝试一下,以确定它的工作方式。
BTW Your first example not equivalent to your second example
顺便说一句,你的第一个例子不等同于你的第二个例子
if float_var:
return formatted_string
else:
return None
This will always return either a formatted string or None. Your first example if you pass in anything that evaluates to False (False, 0, 0.0, "", [] etc) will return that unchanged, so your return type could be string, boolean, list, int, float etc. This is probably not what you want, especially if 0.0 is a legitimate value for float_var. I would change your code to:
这将始终返回格式化字符串或无。您的第一个示例,如果您传入任何计算结果为 False(假、0、0.0、""、[] 等)的内容,将返回不变,因此您的返回类型可以是字符串、布尔值、列表、整数、浮点数等。这是可能不是您想要的,特别是如果 0.0 是 float_var 的合法值。我会将您的代码更改为:
return ('%.0f' % float_var) if isinstance(float_var, float) else None
alternatively:
或者:
try:
return "%.0f" % float_var
except TypeError:
return None
which will work for other integers (and longs) by converting them to float.
通过将它们转换为浮点数,这将适用于其他整数(和长整数)。
回答by Mike Graham
It is not clear what exactly you want to do.
The most literal interpretation would have it work like this
>>> float_var = 4.5 >>> '%.0f' % float_var if float_var else float_var '5' # This is a string >>> float_var = 0.0 >>> '%.0f' % float_var if float_var else float_var 0.0 # This is a float
which I am almost certain you did not want.
I guess you are wanting to check for
None
with "if float_var
"? If so, you always spell it "if foo is not None
", not "if foo
", the former being clearer and less bug-prone.If that iswhat you intended, I suggest you revise your model. Propagating errors by repeatedly returning
None
is a bad thing: it is ugly and bug-prone and non-idiomatic. Use exceptions instead.
Shorter is not always better. Your snippets are not painfully long or unwieldly. In fact, you will want to make them a little longerif you use them to avoid a potential bug.
- Someone may suggest abusing the short-circuiting behavior of
or
for this. However, this makes code harder to read and doesn't allow you to specify betweenNone
and other false values, which often leads to bugs.
- Someone may suggest abusing the short-circuiting behavior of
目前还不清楚你到底想做什么。
最字面的解释会像这样工作
>>> float_var = 4.5 >>> '%.0f' % float_var if float_var else float_var '5' # This is a string >>> float_var = 0.0 >>> '%.0f' % float_var if float_var else float_var 0.0 # This is a float
我几乎可以肯定你不想要。
我猜你想
None
用“if float_var
”来检查?如果是这样,你总是拼写“if foo is not None
”,而不是“if foo
”,前者更清晰,更不容易出错。如果这是您的意图,我建议您修改您的模型。通过重复返回
None
来传播错误是一件坏事:它丑陋、容易出错且不符合习惯。改用异常。
更短并不总是更好。你的代码片段不是很长或很笨拙。事实上,如果你使用它们来避免潜在的错误,你会想要让它们更长一点。
- 有人可能会建议
or
为此滥用短路行为。但是,这会使代码更难阅读,并且不允许您在None
和 其他假值之间指定,这通常会导致错误。
- 有人可能会建议
回答by msw
If you are using are already using v if c else u
you are already using the most readable and efficient ternary operator.
如果您正在使用 are already using,v if c else u
那么您已经在使用最易读和最高效的三元运算符。
There are other waysbut they suffer in readability.
回答by DasIch
float_var and "%.0f" % float_vav
Isn't it awesome?
是不是很棒?