Python 随机数超出范围

0 投票
4 回答
1002 浏览
提问于 2025-04-27 22:45

我正在写一段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

试试这个

name = randoms[number - 1]
0

randint 这个函数需要你给它两个数字,这两个数字是范围的边界,而且这两个边界都是包含在内的。也就是说,如果你的下限是0,那么你的上限应该设置为 len(randoms)-1,这样才能确保你得到的随机数是在你想要的范围内。

1

random.randint(a, b) 这个函数会返回一个在 ab 之间的随机整数,包含 ab 本身。这里,randoms[len(randoms)] 会出错。你可以试试 random.randrange 或者 random.choice 来解决这个问题。

0

你需要知道,有一个特别的功能可以从列表中随机选择一个元素:

random.choice(randoms)

…这个功能应该能实现你想要的效果。

撰写回答