【发布时间】:2021-08-24 04:49:50
【问题描述】:
我遇到了循环问题。我有一个附加随机数的简单for循环,我需要的是,如果一个数字连续出现多次打破for loop,这是一个例子。
import numpy as np
stop = 3
value = []
for i in range(100):
value.append(np.random.randint(0, 2))
print(value)
if value[-stop:] == [0]*stop or value[-stop:] == [1]*stop:
break
这段代码的作用是,我想做一个for loop 100 times,但是如果数字0或数字1在列表的最后连续出现3次,那么循环中断,我怎么能推广到任何随机数,而不必为每个随机值添加无限 or。我尝试使用另一个 for 循环来遍历附加列表中的每个值,但它不起作用,即使达到条件,它也会继续附加随机数:
stop = 3
value = []
for i in range(15):
value.append(np.random.randint(0, 3))
print(value)
for i in value:
if value[-stop:] == [i]*stop:
break
This is what I get in the 10th iteration, here it should stop, since 0 appears three times:
[0, 1, 0, 1, 1, 2, 0, 2, 0, 0, 0]
But it keeps doings iterations and the next one is
[0, 1, 0, 1, 1, 2, 0, 2, 0, 0, 0, 2]
任何想法都将不胜感激,如果有不清楚的地方,请告诉我,我会编辑问题。再次感谢您!
【问题讨论】:
-
[i]*stop不起作用,例如在i=10的循环中,然后[i]*stop将为stop=3提供[10,10,10]
标签: python for-loop if-statement break