Python随机超出范围

时间:2014-10-16 12:41:25

标签: python

我正在编写一个Python 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

4 个答案:

答案 0 :(得分:1)

random.randint(a, b)返回 a b 包含之间的随机整数。在这里,randoms[len(randoms)]发出错误。请改为random.randrangerandom.choice

答案 1 :(得分:0)

试试这个

name = randoms[number - 1]

答案 2 :(得分:0)

randint将范围的包含边界作为参数。因此,如果您的下限为0,您可能希望将上限设置为len(randoms)-1

答案 3 :(得分:0)

您应该知道,从列表中随机选择元素有一个特殊功能:

random.choice(randoms)

......应该做你想要的事。