一行if-condition-assignment [英] One line if-condition-assignment

查看:224
本文介绍了一行if-condition-assignment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

num1 = 10
someBoolValue = True

我需要将 num1 的值设置为 20 如果 someBoolValue True ;否则什么也不做。所以,这是我的代码

I need to set the value of num1 to 20 if someBoolValue is True; and do nothing otherwise. So, here is my code for that

num1 = 20 if someBoolValue else num1

有没有我可以避免 ... else num1 部分让它看起来更干净?相当于

Is there someway I could avoid the ...else num1 part to make it look cleaner? An equivalent to

if someBoolValue:
    num1 = 20

我尝试将其替换为 ...否则传递,如下所示: num1 =如果someBoolValue传递,则为20。我得到的只是语法错误。我也不能省略 ... else num1 部分。

I tried replacing it with ...else pass like this: num1=20 if someBoolValue else pass. All I got was syntax error. Nor I could just omit the ...else num1 part.

谢谢

推荐答案

我不认为这在Python中是可行的,因为你实际上要做的事情可能会扩展到这样的事情:

I don't think this is possible in Python, since what you're actually trying to do probably gets expanded to something like this:

num1 = 20 if someBoolValue else num1

如果排除 else num1 ,您将收到语法错误,因为我非常确定该作业必须实际返回一些内容。

If you exclude else num1, you'll receive a syntax error since I'm quite sure that the assignment must actually return something.

正如其他人已经提到过的那样,你可以做到这一点,但这很糟糕,因为你下次阅读那段代码时可能会让自己感到困惑:

As others have already mentioned, you could do this, but it's bad because you'll probably just end up confusing yourself when reading that piece of code the next time:

if someBoolValue: num1=20

出于同样的原因,我不是 num1 = someBoolValue和20或num1 的忠实粉丝。我必须对该行正在做什么三思而后行。

I'm not a big fan of the num1 = someBoolValue and 20 or num1 for the exact same reason. I have to actually think twice on what that line is doing.

实际达到你想要做的最好的方法是原始版本:

The best way to actually achieve what you want to do is the original version:

if someBoolValue:
    num1 = 20

最好的问题的原因是因为你想要做的事情非常明显,你不会混淆自己,或者其他任何人以后会接触到这些代码。

The reason that's the best verison is because it's very obvious what you want to do, and you won't confuse yourself, or whoever else is going to come in contact with that code later.

另外,作为附注,如果someBoolValue 是有效的Ruby代码, num1 = 20,因为Ruby的工作方式有点不同。

Also, as a side note, num1 = 20 if someBoolValue is valid Ruby code, because Ruby works a bit differently.

这篇关于一行if-condition-assignment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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