条件式是一个按位运算符 https://wiki.python.org/moin/BitwiseOperators比较:
>>> 1 & 1
1
>>> 0 & 1
0
>>> a = 1
>>> a & 1 == 0
False
>>> b = 0
>>> b & 1 == 0
True
正如许多评论所说,对于整数,此条件对于偶数为 True,对于奇数为 False。普遍的写法是if variable % 2 == 0:
or if not variable % 2:
Using timeit
我们可以看到,性能上没有太大差异。
n & 1
("== 0" and "not")
>>> 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" and "not")
>>> 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]
重载运算符:
这俩%
and &
运算符超载。
按位与运算符重载为set https://docs.python.org/2/library/sets.html. s.intersection(t)
相当于s & t
并返回一个“具有 s 和 t 共有元素的新集合”。
>>> {1} & {1}
set([1])
这不会影响我们的条件:
>>> 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: unsupported operand type(s)
对于大多数非整数。
>>> 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'
它被重载为旧版本的字符串插值运算符%-formatting https://docs.python.org/2/library/stdtypes.html#string-formatting。它抛出TypeError: not all arguments converted during string formatting
如果使用字符串进行比较。
>>> 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
如果字符串包含有效的转换说明符,则不会抛出此错误。
>>> modIsEven('%d')
False