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
更新:
这是引文。
核心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.
对
x = x if c else y
使用三元是没有错的,但是,在x = x if x else 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
是最清晰的,应该使用。在我不敢这么做,因为我的真实想法是:
不要微优化。使用你觉得舒服的东西;使用让你的代码最具可读性的东西。如果你觉得这是最可读的,那么三元语句是非常好的。在
上面说
将x重新分配给它本身会有一些小开销。在
^{pr2}$回到我的主要观点:别担心。用你觉得舒服的东西。在
不,没什么问题。
事实上它很像Python。我记得我读过,那是首选的三元等价物(Guido自己)。我看看能不能查到参考资料。
就个人而言,我觉得另一种方式更具可读性,但你没有征求我的个人意见。;)
更新: 这是引文。 核心Python编程,第2版;Wesley J.Hun;Prentice Hall 2007
相关问题 更多 >
编程相关推荐