可以在'for循环'中使用位移运算吗?

3 投票
8 回答
6837 浏览
提问于 2025-04-16 21:49

我有一个用位移操作的C语言for循环,我想把它用Python重新实现。

n = 64
for(int stride = n>>1; stride >0; stride >>=1)
   {...

那么这个循环在Python中会是什么样子的呢?

我知道 n>>1 表示除以2,但我觉得用 range() 来实现这个有点难。

8 个回答

5

Amadan的回答非常准确。

如果你经常使用这种模式,我建议把它提取成一个简单的生成器函数,这样可以在for循环中重复使用:

>>> def strider(n):
...     stride = n >> 1
...     while stride > 0:
...         yield stride
...         stride >>= 1
...
>>> for n in strider(64):
...     print n
...
32
16
8
4
2
1
5

想得简单点:

>>> n = 64
>>> while n:
...     print n
...     n = n >> 1
...
64
32
16
8
4
2
1
3

所有的 for(;;) 循环都可以改写成 while 循环,反之亦然。

n = 64
stride = n >> 1
while stride > 0:
    # stuff
    stride >>= 1

已编辑以反映原始内容的变化

撰写回答