2014-10-16 5 views
0

파이썬 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 
+0

'randint'를'randrange'로 바꾸면 -'randint (a, b)'**는'b' **를 포함합니다. – jonrsharpe

답변

0

당신은 ramdonly 목록에서 요소를 선택하는 특별한 기능이 있다는 것을 알고 있어야합니다

random.choice(randoms) 

이 ... 당신이하고자하는 일을한다.

1

random.randint(a, b) 반환 임의의 정수를 포함 B 사이. 여기에서 randoms[len(randoms)]이 오류를 발생시키고 있습니다. 대신 random.randrange 또는 random.choice을 시도하십시오.

0

randint의 범위에 대한 인수로 포함 경계를 취하십시오. 따라서 하한값이 0이면 상한값을 len(randoms)-1으로 설정하고 싶을 것입니다.