自引用三元 [英] self-referencing ternary

查看:76
本文介绍了自引用三元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了一段时间了:

I've been doing this for a while:

x = x if x else y

在x可能为 None False 0 '' [] {} .

In all sorts of contexts where x might be None, False, 0, '', [], or {}.

我知道纯粹主义者宁愿我:

I know the purists would rather I:

if not x:
    x = y

但请记住,那不是我的问题.我的问题是:

but forget that, that's not my question. My question is:

除了x是y以外,是否还有 x = x的错误"信息?具体来说,可以像这样进行三元自赋值.

Is there anything 'wrong' with x = x if x else y besides the fact it's a ternary? Specifically, is it ok to have a ternary self-assign like that.

注意

我的问题是 not x = x(如果C否则y 可以).我知道是这样.

My qustion is not is x = x if C else y ok. I know it is.

非常感谢

推荐答案

在c = y的情况下,对 x = x使用三元数并没有错,但是对于 x= x,如果x else y ,则逻辑确实会减少为

There is nothing wrong with using ternary for x = x if c else y, however, in the case of x = x if x else y the logic really does just reduce to

x = x or y

这是因为在Python中, x或y 的计算结果为

This is because in Python x or y evaluates to 'if x is false, then y, else x'

所以 x如果x else y == y如果不是x else x == x或y

So x if x else y == y if not x else x == x or y

很明显, x或y 最清晰,应该使用.

Obviously, x or y is the clearest and should be used.

这篇关于自引用三元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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