[英]Python: What does >>= do?
I'm learning python and I stumbled upon something I don't understand. 我正在学习python,却偶然发现了我不了解的东西。
For instance: 例如:
x = 50
while x:
print(x)
x >>= 1
Outputs: 输出:
50
25
12
6
3
1
So I infer that it divides by two and rounds to the left if it's not an integer or something similar. 因此,我推断如果不是整数或类似的数字,它将除以2并向左舍入。
But when I change it to x >>= 3 for instance the output is: 但是,例如,当我将其更改为x >> = 3时,输出为:
50
6
Can someone please explain what >>= does? 有人可以解释>> =做什么吗?
If so, what are useful applications of this kind of operator. 如果是这样,这种运算符有什么有用的应用程序。
>>=
is the augmented assignment statement for the >>
right-shift operator . >>=
是>>
右移运算符的扩充赋值语句 。 For immutable types such as int
it is exactly the same thing as: 对于
int
这样的不可变类型,它与以下内容完全相同 :
x = x >> 1
right-shifting the bits in x
one step to the right. 将
x
的位右移一位。
You can see what it does if you print the binary representation of x
first: 如果先打印
x
的二进制表示形式,则可以看到它的作用:
>>> x = 50
>>> format(x, '08b')
'00110010'
>>> x >>= 1
>>> format(x, '08b')
'00011001'
>>> x = 50
>>> x >>= 3
>>> format(x, '08b')
'00000110'
>>> x
6
Each shift to the right is equivalent to a floor division by 2; 每次向右移动等于将地板除以2; 3 shifts thus is as if
x
was divided by 2 to the power 3, then floored to an integer. 因此,将3个移位视为
x
被2除以3的幂,然后下限为整数。
The complementary operator is the left-shift <<
operator, multiplying the left-hand integer by 2; 补数运算符是左移
<<
运算符,将左侧整数乘以2; it is a binary power-of-two operator: 它是二进制的2的幂的运算符:
>>> x = 6
>>> format(x, '08b')
'00000110'
>>> x <<= 3
>>> x
48
>>> format(x, '08b')
'00110000'
Augmented assignment operators can differ in behaviour when applied to mutable types such as a list object, where the operation can take place in-place . 扩展赋值运算符应用于可变类型(例如列表对象)的可变行为时,行为可以就地进行 。 For example,
listobj += [1, 2, 3]
will alter listobj
itself, not create a new list object, as if listobj.extend([1, 2, 3])
was called. 例如,
listobj += [1, 2, 3]
会更改listobj
本身,而不创建新的列表对象,就像listobj.extend([1, 2, 3])
。
This is augmented assignment with the right shift operator . 这是使用右移运算符进行的 扩充分配 。
x >>= 1
is shorthand for x = x >> 1
. x >>= 1
是x = x >> 1
简写。
x >>= k
divides by 2**k
(ie 2
raised to the k
-th power). x >>= k
除以2**k
(即2
升至第k
幂)。
Thus, x >>= 3
is the integer division by eight. 因此,
x >>= 3
是八分的整数。
It's the binary right shift operator. 它是二进制右移运算符。 For example, if you have
0100b
, and you do: 0100b >> 2
, then as a result you will have the number 0001b
(you've shifted the one two positions to the right). 例如,如果您有
0100b
,并且您执行了: 0100b >> 2
,那么结果将是数字0001b
(您将其中两个位置向右移动了)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.