执行 "bit iterator" 但有 3 个状态的代码

Code to do a "bit iterator" but with 3 states

我想做一个遍历 3 个状态的计数器。我知道如何使用位运算符 i^=1.

对 2 个状态执行此操作

我想知道是否有一种方法可以做到类似但具有三种状态?

我意识到我可以做到:

i = 0
while
   if(i==3)
       i = 0
   do stuff here
   i++

但我希望有更优雅、更高效的东西。我在想模数技巧之类的。

(我现在用的是python)

for i in itertools.cycle([1,2,3]):
    target.set_state(i)

也许吧??

itertools对你有用吗?

import itertools
states = itertools.cycle([0, 1, 2])
while True:
  i = states.next()
  <do stuff>

这是我在数学和语言上独立得出的结论。对于超过 3 个的集合,我相信您需要更改素数和偏移量。

i = 1
while
     do stuff
     i = 7%(3+(abs(i-3)))