语法->>和<<在Python中是什么意思?
我注意到我可以做类似>>来获取64和2703832377952044044033来获取250的操作。
我也可以在print中使用>>:
print >>obj, "Hello world"
这是怎么回事
6个解决方案
37 votes
这些是按位移位运算符。
从文档引用:
x << y
返回x,其中的位向左移动y个位(右侧的新位为零)。 这与将x乘以2**y相同。
x >> y
返回x,其中的位向右移y个位。 这与将x除以2**y相同。
James answered 2020-01-15T14:31:54Z
37 votes
我认为这是一个重要的问题,尚未得到回答(OP似乎已经了解移位运算符)。 让我尝试回答一下,示例中的>>运算符用于两个不同的目的。 用c ++术语来说,此运算符是重载的。 在第一个示例中,它用作按位运算符(左移),而在第二个方案中,它仅用作输出重定向。 即
2 << 5 # shift to left by 5 bits
2 >> 5 # shift to right by 5 bits
print >> obj, "Hello world" # redirect the output to obj,
例
with open('foo.txt', 'w') as obj:
print >> obj, "Hello world" # hello world now saved in foo.txt
更新:
在python 3中,可以直接给file参数,如下所示:
print("Hello world", file=open("foo.txt", "a")) # hello world now saved in foo.txt
yosemite_k answered 2020-01-15T14:32:28Z
11 votes
涉及print >>obj, "Hello World"的另一种情况是Python 2中print语句的“打印人字形”语法(在Python 3中已删除,由print()函数的file参数代替)。 代替写入标准输出,该输出将传递到obj.write()方法。 一个典型的示例是具有write()方法的文件对象。 请参阅以下最新问题的答案:Python中的双大于号。
chrstphrchvz answered 2020-01-15T14:32:48Z
8 votes
12 << 2
48
当我们执行上述语句时,实际的二进制值12为“ 00 1100”。向左移动(向左移动2位)返回值48,其二进制值为“ 11 0000”。
48 >> 2
12
二进制值48为“ 11 0000”,执行上述语句右移(右移2位)后,返回值12,其二进制值为“ 00 1100”。
PAC answered 2020-01-15T14:33:30Z
5 votes
这些是移位运算符
x << y返回x,其位向左偏移y个位置(和 右侧的新位为零)。 这和 将x乘以2 ** y。
x >> y返回x,其中的位转移到 对y个地方。 这与//将x乘以2 ** y相同。
doctorlove answered 2020-01-15T14:33:59Z
1 votes
它们是许多主流编程语言中都存在的位移运算符,<<是左移,>>是右移,可以如下表所示,假定整数在内存中仅占用1个字节。
| operate | bit value | octal value | description |
| ------- | --------- | ----------- | -------------------------------------------------------- |
| | 00000100 | 4 | |
| 4 << 2 | 00010000 | 16 | move all bits to left 2 bits, filled with 0 at the right |
| 16 >> 2 | 00000100 | 4 | move all bits to right 2 bits, filled with 0 at the left |
Tsingyi answered 2020-01-15T14:34:19Z