python,在列表中添加和覆盖值

python,在列表中添加和覆盖值,python,python-3.x,Python,Python 3.x,我正在制作一个名为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: fo

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

但我不知道该怎么做。谢谢你的帮助

您可能希望将其更改为:

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
    变量取出(您不应该这样做)
  • 修正了实际添加到马的线条
  • 已将所有马初始化为0
  • 将带有循环出口的线放在循环内,以便在循环过程中退出
  • 取出
    flag==False
    并将其替换为
    not flag:
    • 从PEP 8开始:
      不要使用==将布尔值与真值或假值进行比较。

    • 您可以完全避免
      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\u pos
      而不是
      foo
      ,事情会更容易理解。我希望您在每次更新马匹位置后都添加动画显示步骤!:)

      eval(输入())
      :避免。改为使用
      int(input())
      问题是在循环外使用
      i
      索引。真奇怪…你想在foo中插入多少个iTen?在此代码中,您将插入n倍的元素!可能是这样的:if-foo[i]>=5280:Is:if-i>=5280:谢谢你的帮助。我对你写的东西有个问题。行foo=[0代表范围内的i(马)]做什么?我知道它列出了一个名为foo的列表,但是,0代表I,但是把我搞砸了。它是否将horses变量的计数从零开始?因此,如果键入3匹马,则列表的索引为0,1,2,而不是像我的原始代码中那样的0,1,2,3?@DrJenkins:
      [0代表范围内的i(马)]
      生成一个包含整数
      马所说的数量的零的列表。未使用
      i
      的值<代码>范围(n)
      生成0,1,。。。n-1。生成
      n
      零列表的更惯用方法是
      [0]*n