2017-03-03 97 views
1

我正在製作一個名爲foo的列表,其中存儲n個隨機值。我希望能夠創建一個連續增加隨機值並將新值存儲在foo中的循環[i],這是迄今爲止我的代碼。任何時候我運行這個我都無法退出while循環。python,添加和覆蓋列表中的值

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 

我覺得這是不工作的原因是因爲我沒有實際添加到存儲在富[i]於行

 foo.insert(i, random.randrange(4,41)) 

的價值,但我無法弄清楚什麼代替。謝謝你的幫助!

+2

'eval(input())':avoid。做'int(input())而不是' –

+0

問題是你在循環之外使用你的'i'索引。這真的很奇怪...... –

+0

你想在foo中插入多少itens?在此代碼中,您將插入n次元素!如果foo [i]> = 5280: Is:if i> = 5280: –

回答

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 

我:

  • 刪除a變量,你沒有初始化
  • 拿出使用外循環i變量(你不應該這樣做)
  • 固定線實際添加到馬
  • 初始化所有的馬匹在0
  • 把符合循環內的循環退出,因此循環
  • 拿出flag == Falsenot flag:
    • 取代它從PEP 8時退出:Don't compare boolean values to True or False using == .
+0

'foo [i] + = random ...'讀得更好。 – 9000

+0

@ 9000沒有注意到,謝謝。 – rassar

+0

感謝您的幫助。我對你寫的內容有疑問。這條線foo = [0(對於範圍內的我(馬))是做什麼的?我知道它製作了一個名爲foo的列表,但是,對於我來說,0卻讓我感到困惑。它是否在零時開始計數馬變量?所以相反,如果輸入3匹馬,列表中的索引0,1,2不是0,1,2,3就像我的原始代碼? – DrJenkins

1

可避免過度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,事情會更容易理解。我希望你會在每次馬匹位置更新後添加一個動畫顯示步驟! :)