蟒蛇? (有条件/三元)运算符的任务 [英] python ? (conditional/ternary) operator for assignments

查看:179
本文介绍了蟒蛇? (有条件/三元)运算符的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C和许多其他语言有一个条件(又名三元)运营商。这使您可以根据条件的真相,这使得前pressions,包括作业,两个值之间做出非常简洁的选择非常简洁。

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.

我想这是因为我发现我的code有很多是需要四线在Python有条件分配:

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

而在C中,它将会是:

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.

我喜欢的条件运算符的简洁性,因为它让事情掠过code时,我认为非战略从分散我的注意力。

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

所以,在Python,还有我介绍他们,你可以用它来获得分配成一条线近似条件运算符的优势什么花样?

推荐答案

Python有这样一个操作符:

Python has such an operator:

variable = something if condition else something_else

另外,虽然不建议(见@ karadoc的评论)

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

variable = (condition and something) or something_else

这篇关于蟒蛇? (有条件/三元)运算符的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆