2014-10-17 89 views
0

我在Python 3.3.3中編寫了一個代碼,如果你輸入12並且確保重複最多的團隊只重複一次以上至少在重複。如果已經這樣做:Python - 「random」error

import random 
    teams =[] 
    randoms = [] 
    team = 0 
    amount = 1 
    while team != "done": 
     team = input("Please enter team name " + str(amount) +" or enter 'done' if you have finished.\n") 
     if team != "done": 
      teams.append(team) 
      randoms.append(team) 
      amount = amount + 1 
    length = len(teams) 
    times =0 
    while len(teams) != 32: 
     while len(teams) <= 32-length: 
      for x in range (0,length+1): 
       teamname = teams[x] 
       teams.append(teamname) 
     else: 
      choice = random.choice(randoms) 
      teams.append(choice) 
      randoms.remove(choice) 
     teams.sort() 
    for x in range(0,len(teams)): 
     print (teams[x]) 

我運行該程序,然後輸入12隊,然後完成。 它配備了以下消息:

Traceback (most recent call last): 
    File "C:\Python33\lib\random.py", line 248, in choice 
    i = self._randbelow(len(seq)) 
    File "C:\Python33\lib\random.py", line 224, in _randbelow 
    r = getrandbits(k)   # 0 <= r < 2**k 
ValueError: number of bits must be greater than zero 


During handling of the above exception, another exception occurred: 


Traceback (most recent call last): 
    File "[File location]", line 30, in <module> 
    choice = random.choice(randoms) 
    File "C:\Python33\lib\random.", line 250, in choice 
    raise IndexError('Cannot choose from an empty sequence') 
IndexError: Cannot choose from an empty sequence 

這是什麼意思,如何解決這一問題?

+1

我會假設randoms是一個空列表,當你將它傳遞給random.choice – Noelkd 2014-10-17 07:48:43

+1

你能整理你的代碼和回溯縮進,謝謝 – EdChum 2014-10-17 07:48:45

+0

你使用的是什麼版本的Python? – 2014-10-17 07:52:42

回答

0

當random.choice()函數中的數組爲空時發生該錯誤。我建議你使用Python調試器來確定數組何時完全爲空。它可以幫助您添加一行代碼來在每個循環中打印len(團隊),以查看編碼混亂的位置。它可能像> vs> =一樣簡單。

希望這會有所幫助!