我正在创建一个名为foo的列表,其中存储了n个随机值。我希望能够创建一个循环,不断添加随机值并将新值存储在foo [i]中这是我的代码到目前为止。无论何时我运行这个,我都无法退出while循环。
import random
foo=[]
i=0
flag = False
print("How many horses do you want to race?")
horses = eval(input())
print (horses)
while flag == False:
for i in range(horses):
foo.insert(i, random.randrange(4,41))
print(a)
if foo[i] >= 5280:
flag = True
else:
i=i+1
我认为这不起作用的原因是因为我实际上并没有在行中添加存储在foo [i]中的值
foo.insert(i, random.randrange(4,41))
但我无法弄明白该做什么。谢谢你的帮助!
答案 0 :(得分:1)
您可能想将其更改为:
import random
i=0
flag = False
print("How many horses do you want to race?")
horses = int(input())
print (horses)
foo = [0] * horses #initialize horse values
while not flag:
for i in range(horses):
foo[i] += random.randrange(4,41) #move the horse a random amount
if foo[i] >= 5280:
flag = True #a horse has won
break #exit the loop
I:
a
变量i
变量取出(你不应该这样做)flag == False
并将其替换为not flag:
Don't compare boolean values to True or False using == .
答案 1 :(得分:1)
您可以完全避免显式循环foo = [0 for _ in range(horses)] # or even [0] * horses
over_the_line = [] # Index(es) of horses that have crossed the line.
while not over_the_line:
foo = [pos + random.randint(...) for pos in foo] # Move them all.
over_the_line = [i for (i, pos) in enumerate(foo) if pos >= 5280]
# Now you can decide who from over_the_line is the winner.
。
horse_pos
此外,如果您调用变量foo
而不是python manage.py dumpdata --format json -e app1 -e app2
,则事情会更容易理解。我希望您在每次马位置更新后添加动画显示步骤! :)