基于2值Python的循环

2024-10-01 07:46:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个变量

例:

compt = 9
first = 3
second = 2

然后我想根据compnt长度循环,然后根据变量first和second更改状态on或off

我想要的输出:

On
On
On
Off
Off
On
On
On
Off

我目前的代码是:

x,y=0,0
for i in range(0,compt):
   if x != first:
      print("On")
      x+=1
   elif x == first and y != second:
      print("Off")

但是上面代码的输出是

On
On
On
Off
Off
On
On
On
On

有人能帮我解决我的问题吗,谢谢


Tags: 代码inforifon状态rangefirst
3条回答
from itertools import cycle, islice

total = 9

first = 3
second = 2

sequence = ["On" for _ in range(first)] + ["Off" for _ in range(second)]
print(sequence)

result = islice(cycle(sequence), 0, total)

for state in result:
    print(state)

输出:

['On', 'On', 'On', 'Off', 'Off']
On
On
On
Off
Off
On
On
On
Off

另一个与itertools有关的变体:

from itertools import cycle, repeat, chain

compt = 9
first = 3
second = 2

on = repeat("On", first)    # ["On", "On", ..] 
off = repeat("Off", second) # ["Off", "Off", ..]

for status in cycle(chain(on, off)): # combine on and off and repeat
    print(status)

    # break when compt is exhausted
    compt -= 1
    
    if compt <= 0:
        break

compt = 9
first = 3
second = 2

for i in range(compt):
    max_val = first + second
    if i % max_val < first:
        print("on")
    else:
        print("off")

输出:

on
on
on
off
off
on
on
on
off

相关问题 更多 >