如何继续执行此代码,直到最后一个元素"4"出现在输出列表中



当我执行下面的代码时,我得到

[0,0,1,2,2,3,4,4,5,6,7]

但是,我希望这样做:

[0,0,1,1,2,2,2,2,3,3,4]

我希望输出,因为print应该只发生到列表的最后一个元素(tails[-1](等于 4。

import numpy as np
np.random.seed()
tails = [0]
for x in range(10):
coin = np.random.randint(0, 2)
tails.append(tails[x] + coin)
if tails[-1] == 4:
print(tails)

在打印tails中的最后一个元素后尝试break关键字,如果它是4

if tails[-1] == 4:
print(tails)
break

然后可以尝试使用sys.exit()退出脚本。

import numpy as np
np.random.seed()
tails = [0]
def loop():
for x in range(10):
coin = np.random.randint(0, 2)
tails.append(tails[x] + coin)
return tails
while True:
loop()
if tails[-1] == 4:
print(str(tails)+' - !! success !!')
break
else :
x = 1
for i in range(10):
for i in range(1, x + 1):
b = tails.pop(i)

这是我期望的代码,我自己解决了它。

(对不起,伙计们不知道如何提出正确的问题。

这是你的代码(添加了中断(

import numpy as np
np.random.seed()
tails = [0]
for x in range(10):
coin = np.random.randint(0, 2)
tails.append(tails[x] + coin)
if tails[-1] == 4:
print(tails)
break            # breaks out the loop

就这么简单!

相关内容

最新更新