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
這是什麼意思,如何解決這一問題?
我會假設randoms是一個空列表,當你將它傳遞給random.choice – Noelkd 2014-10-17 07:48:43
你能整理你的代碼和回溯縮進,謝謝 – EdChum 2014-10-17 07:48:45
你使用的是什麼版本的Python? – 2014-10-17 07:52:42