python,在lis中添加和覆盖值

2024-09-27 04:29:23 发布

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

我正在制作一个名为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))

但我不知道该怎么办。谢谢你的帮助!你知道吗


Tags: 代码importfalse列表foorandommanyhow
2条回答

您可以完全避免foo上的显式循环。你知道吗

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,事情会更容易理解。我希望你会添加一个动画显示步骤后,每匹马的位置更新!:)

您可能要将其更改为:

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

一:

  • 删除了未初始化的a变量
  • 在循环外使用i变量取出(您不应该这样做)
  • 修正了实际添加到马的行
  • 在0初始化了所有的马
  • 将带有循环出口的线放在循环内,以便在循环期间退出
  • 取出flag == False换成not flag:
    • 从政治公众人物8:Don't compare boolean values to True or False using == .

相关问题 更多 >

    热门问题