python ? (conditional/ternary) operator for assignments [duplicate]

泄露秘密 提交于 2019-12-03 18:43:57

问题


C and many other languages have a conditional (aka ternary) operator. This allows you to make very terse choices between two values based on the truth of a condition, which makes expressions, including assignments, very concise.

I miss this because I find that my code has lots of conditional assignments that take four lines in Python:

if condition:
    var = something
else:
    var = something_else

Whereas in C it'd be:

var = condition? something: something_else;

Once or twice in a file is fine, but if you have lots of conditional assignments the number of lines explode and, worst of all, the eye is drawn to them.

I like the terseness of the conditional operator because it keeps things I deem un-strategic from distracting me when skimming the code.

So, in Python, are there any tricks you can use to get the assignment onto a single line to approximate the advantages of the conditional operator as I outlined them?


回答1:


Python has such an operator:

variable = something if condition else something_else

Alternatively, although not recommended (see @karadoc's comment):

variable = (condition and something) or something_else



回答2:


In older Python code, you may see the trick:

condition and something or something_else

however, this has been superseded by the vastly superior ... if ... else ... construct:

something if condition else something_else


来源:https://stackoverflow.com/questions/3091316/python-conditional-ternary-operator-for-assignments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!