Python 为什么调用随机整数时会出现值错误?

Python 为什么调用随机整数时会出现值错误?,python,Python,我正在写一个程序,你输入一个短语,比如“听我说”,然后它输出一个字谜短语。示例:“哼哼耳朵”。我写的一个函数,叫做FindRandomWordofLength,t=有问题。当我调用randint时,我总是得到一个值错误。我通过创建一个名为test_random_word的脚本来隔离这个问题。有人能解释这个错误的来源吗 import random def CreateDictionary(text): """ :param text: A txt file of English

我正在写一个程序,你输入一个短语,比如“听我说”,然后它输出一个字谜短语。示例:“哼哼耳朵”。我写的一个函数,叫做FindRandomWordofLength,t=有问题。当我调用randint时,我总是得到一个值错误。我通过创建一个名为test_random_word的脚本来隔离这个问题。有人能解释这个错误的来源吗

import random

def CreateDictionary(text):
    """
    :param text: A txt file of English words, one word per line.
    :return: Dictionary with keys: "2", "3", "4", ..."12" denoting the length of the words, and values are lists of
    words with the appropriate length.
    """
    dict = {"2": [], "3": [], "4": [], "5": [], "6": [], "7": [], "8": [], "9": [], "10": [], "11": [], "12": []}
    with open(text, "r") as fileObject:
        for line in fileObject:
            if 1 < len(line.strip()) < 12:
                dict[str(len(line.strip()))].append(line.strip())

    return dict


def FindRandonmWordofLength(dict, length):
    """
    :param dict: a dictionary constructed from the CreateDictionary function.
    :param length: an integer value between 3 and 12, including endpoints.
    :return: a random word from the dictionary of the requested length.
    """
    length_of_list = len(dict[str(length)])
    random_num = random.randint(1, length_of_list - 1)
    return dict[str(length)][random_num]

dict = CreateDictionary("20k.txt")

for i in range(1000000):
    random_length = random.randint(3, 12)
    word = FindRandonmWordofLength(dict, random_length)

    print("The random word is: " + word)
随机导入
def CreateDictionary(文本):
"""
:param text:英文单词的txt文件,每行一个单词。
:return:Dictionary,其中键“2”、“3”、“4”、“12”表示单词的长度,值是
适当长度的单词。
"""
dict={“2”:[],“3”:[],“4”:[],“5”:[],“6”:[],“7”:[],“8”:[],“9”:[],“10”:[],“11”:[],“12”:[]}
以open(文本,“r”)作为文件对象:
对于fileObject中的行:
如果1
我经常看到这个错误

返回self.randrange(a,b+1)文件 “C:\Users\kevoh\AppData\Local\Programs\Python\Python37-32\lib\random.py”, 第200行,在随机范围内 raise VALUERROR(“randrange()的空范围(%d,%d,%d)”%(istart,istop,width))VALUERROR:randrange()的空范围(1,0, -(一)


当使用
random.randint(a,b)
时,您必须确保
错误消息还应显示代码中的哪一行出现问题,而不仅仅是标准模块中的哪一行出现问题。Python中的列表编号为零,而不是一。因此,如果使用
randint(1,列表的长度-1)
,则可以获得randint(1,1)正如您在消息中看到的,它可以使范围变为空。如果您想从列表中获取随机元素,那么模块
random
具有更好的函数,比如
random.choice()
print-
length\u of_list=len(dict[str(length)])
length可能有一个
0
值0-1=-1,您应该处理它it@furas++for
random.choice()
。虽然
randint
在两端都包含,但是
randint(1,1)
返回1。该错误似乎源于
randint(1,0)
。。。