奇怪如果声明 [英] Strange if statement
问题描述
我在别人的代码中找到了这个奇怪的 if
-statement:
I found this strange if
-statement in somebody else’s code:
if variable & 1 == 0:
我不明白。它应该有两个 ==
,对吧?
I don't understand it. It should have two ==
, right?
有人可以解释一下吗?
推荐答案
条件是按位运算符比较:
>>> 1 & 1
1
>>> 0 & 1
0
>>> a = 1
>>> a & 1 == 0
False
>>> b = 0
>>> b & 1 == 0
True
As许多评论说,对于整数,这个条件对于平均而言是真的,对于赔率是假的。写这个的流行方式是如果变量%2 == 0:
或如果不是变量%2:
使用 timeit
我们可以看到性能差异不大。
Using timeit
we can see that there isn't much difference in performance.
n& 1
(== 0和不是)
>>> timeit.Timer("bitwiseIsEven(1)", "def bitwiseIsEven(n): return n & 1 == 0").repeat(4, 10**6)
[0.2037370204925537, 0.20333600044250488, 0.2028651237487793, 0.20192503929138184]
>>> timeit.Timer("bitwiseIsEven(1)", "def bitwiseIsEven(n): return not n & 1").repeat(4, 10**6)
[0.18392395973205566, 0.18273091316223145, 0.1830739974975586, 0.18445897102355957]
n%2
(== 0和不是)
>>> timeit.Timer("modIsEven(1)", "def modIsEven(n): return n % 2 == 0").repeat(4, 10**6)
[0.22193098068237305, 0.22170782089233398, 0.21924591064453125, 0.21947598457336426]
>>> timeit.Timer("modIsEven(1)", "def modIsEven(n): return not n % 2").repeat(4, 10**6)
[0.20426011085510254, 0.2046220302581787, 0.2040550708770752, 0.2044820785522461]
重载运营商:
%
和&
运算符都被重载。
set
一>。 s.intersection(t)
相当于 s& t
并返回具有s和t共有元素的新集合。
The bitwise and operator is overloaded for set
. s.intersection(t)
is equivalent to s & t
and returns a "new set with elements common to s and t".
>>> {1} & {1}
set([1])
这不会影响我们的条件:
This doesn't effect our conditional:
>>> def bitwiseIsEven(n):
... return n & 1 == 0
>>> bitwiseIsEven('1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in bitwiseIsEven
TypeError: unsupported operand type(s) for &: 'str' and 'int'
>>> bitwiseIsEven({1})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in bitwiseIsEven
TypeError: unsupported operand type(s) for &: 'set' and 'int'
模数运算符也将抛出 TypeError:不支持的操作数类型
对于大多数非ints。
The modulo operator will also throw TypeError: unsupported operand type(s)
for most non-ints.
>>> def modIsEven(n):
... return n % 2 == 0
>>> modIsEven({1})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in modIsEven
TypeError: unsupported operand type(s) for %: 'set' and 'int'
它作为旧的 % - 格式化
。它抛出 TypeError:在字符串格式化期间不是所有参数都被转换
如果字符串用于比较。
It is overloaded as a string interpolation operator for the old %-formatting
. It throws TypeError: not all arguments converted during string formatting
if a string is used for the comparison.
>>> modIsEven('1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in modIsEven
TypeError: not all arguments converted during string formatting
如果字符串包含有效的转换说明符,则不会抛出。
This won't throw if the string includes a valid conversion specifier.
>>> modIsEven('%d')
False
这篇关于奇怪如果声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!