파이썬 3.3.3에 코드를 작성하여 말을 12 개 입력하면 32 개 팀 목록을 만들고 가장 많이 반복되는 팀이 다음과 같이 한 번만 반복되도록합니다. 적어도 반복되었습니다. 이 작업을 수행 한 경우 :범위를 벗어난 파이썬 임의 번호
import random
if run == '1':
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)
while len(teams) != 32:
if len(teams) < 32-length:
for x in range (0,length):
teams.append(teams[x])
else:
number = random.randint(0,len(randoms))
name = randoms[number]
teams.append(name)
randoms.remove(name)
teams.sort()
for x in range(0,len(teams)):
print (teams[x])
나는 프로그램을 실행하고 12 개 팀을 입력 한 다음 완료했습니다. 다음과 같은 메시지가 나타납니다 :
line 29, in <module>
name = randoms[number]
IndexError: list index out of range
나는이 숫자가 배열의 길이 범위에 있지 않다는 것을 알고 있지만 어떻게 수정합니까? 의견을 보내 주셔서 감사합니다. 지금이 :
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])
그러나이 오류를 반환
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 "C:(File)", line 30, in <module>
choice = random.choice(randoms)
File "C:\Python33\lib\random.py", line 250, in choice
raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence
'randint'를'randrange'로 바꾸면 -'randint (a, b)'**는'b' **를 포함합니다. – jonrsharpe