gpt4 book ai didi

python - 理解 Python 按位、算术和 bool 运算符

转载 作者:太空宇宙 更新时间:2023-11-04 08:53:38 24 4
gpt4 key购买 nike

我是 Python 新手,无法理解这一点。有人可以帮我分解声明吗?

n和parity都是整数

n += parity != n & 1

最佳答案

表达式被计算为n += (parity != (n & 1)),结果为:

  • n & 1 是一个位掩码,它将整数n 掩码到最低有效位。如果 n 为奇数,则为 1,如果为偶数,则该位为 0

  • parity != 0parity != 1 产生一个boolean 结果,TrueFalse,如果 parity 不等于右侧的 01,则发出信号。

  • 生成的 TrueFalse 加到 n 中,就好像您做的那样 n = n + True n = n + False。 Python bool 类型是int子类False 的整数值为0True 1 的值。

代码,本质上就是根据parity的值,在n上加上01如果 n 当前是偶数或奇数。

一个简短的演示可能会更好地说明这一点。

首先,n & 1 产生 01:

>>> n = 10  # even
>>> bin(n) # the binary representation of 10
'0b1010'
>>> n & 1 # should be 0, as the last bit is 0
0
>>> n = 11 # odd
>>> bin(n) # the binary representation of 11
'0b1011'
>>> n & 1 # should be 1, as the last bit is 1
1

接下来,parity != 0parity != 1 部分;请注意,我假设 parity 仅限于 01,它具有其他值确实没有意义:

>>> parity = 0
>>> parity != 1
True
>>> parity != 0
False
>>> parity = 1
>>> parity != 1
False
>>> parity != 0
True

最后, bool 值是整数:

>>> isinstance(True, int)
True
>>> int(True)
1
>>> 10 + True
11
>>> 10 + False
10

这个公式看起来像是在计算一个 CRC checksum .

关于python - 理解 Python 按位、算术和 bool 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32618712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com