自参考三值

2024-03-29 13:41:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经做了一段时间了:

x = x if x else y

在各种上下文中,x可能是NoneFalse0''[]、或{}。在

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

^{pr2}$

但别忘了,这不是我的问题。我的问题是:

除了它是三元值之外,x = x if x else y还有什么不对吗?具体地说,这样的三元自赋值可以吗。在

注意

我的问题是x = x if C else y好的。我知道是的。在

非常感谢


Tags: nonefalseifelse赋值主义者pr2
3条回答

x = x if c else y使用三元是没有错的,但是,在x = x if x else y的情况下,逻辑实际上只是简化为

x = x or y

这是因为在Python中,x or y的计算结果是'if x is false, then y, else x'

所以x if x else y==y if not x else x==x or y

显然,x or y是最清晰的,应该使用。在

我不敢这么做,因为我的真实想法是:

不要微优化。使用你觉得舒服的东西;使用让你的代码最具可读性的东西。如果你觉得这是最可读的,那么三元语句是非常好的。在

上面说

ben@nixbox:~$ python3 -m timeit 'x = 1; x=x if x else 2'
10000000 loops, best of 3: 0.0345 usec per loop
ben@nixbox:~$ python3 -m timeit '''
> x=1
> if not x:
>     x=2
> '''
10000000 loops, best of 3: 0.0239 usec per loop

将x重新分配给它本身会有一些小开销。在

^{pr2}$

回到我的主要观点:别担心。用你觉得舒服的东西。在

不,没什么问题。
事实上它很像Python。我记得我读过,那是首选的三元等价物(Guido自己)。我看看能不能查到参考资料。
就个人而言,我觉得另一种方式更具可读性,但你没有征求我的个人意见。;)

更新: 这是引文。 核心Python编程,第2版;Wesley J.Hun;Prentice Hall 2007

If you are coming from the C/C++ or Java world, it is difficult to ignore or get over the fact that Python has not had a conditional or ternary operator (C ? X : Y) for the longest time. [...] Guido has resisted adding such a feature to Python because of his belief in keeping code simple and not giving programmers easy ways to obfuscate their code. However, after more than a decade, he has given in, mostly because of the error-prone ways in which people have tried to simulate it using and and or - many times incorrectly. According to the FAQ, the one way of getting it right is (C and [X] or [Y])[0]. The only problem was that the community could not agree on the syntax. (You really have to take a look at PEP 308 to see all the different proposals.) This is one of the areas of Python in which people have expressed strong feelings. The final decision came down to Guido choosing the most favored (and his most favorite) of all the choices, then applying it to various modules in the standard library. According to the PEP, "this review approximates a sampling of real-world use cases, across a variety of applications, written by a number of programmers with diverse backgrounds." And this is the syntax that was finally chosen for integration into Python 2.5: X if C else Y.

相关问题 更多 >