我正在编写一个Python 3.3.3中的代码,如果你输入12,那么会列出32个团队,并确保重复次数最多的团队只重复一次,而不是重复次数最多。如果这样做了:
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
这是什么意思,我该如何解决这个问题?
答案 0 :(得分:0)
random.choice()函数中的数组为空时发生该错误。我建议您使用Python调试器来确定数组何时完全为空。它可以帮助您添加一行代码来打印len(团队)每个循环,以查看编码的混乱程度。它可以像&gt;一样简单。与&gt; =。
希望这有帮助!