Python抛出列表索引超出范围错误

Python抛出列表索引超出范围错误,python,list,for-loop,list-comprehension,Python,List,For Loop,List Comprehension,我试着理解列表,但不久就失败了。有人能帮忙吗 我在Windows10上使用Python3.7,我不明白为什么我的代码不能工作 import random import lists # includes the lists in the __init__ method class PassGen: def __init__(self): password = [] self.vowel_list = lists.vowel_list s

我试着理解列表,但不久就失败了。有人能帮忙吗

我在Windows10上使用Python3.7,我不明白为什么我的代码不能工作

import random
import lists  # includes the lists in the __init__ method

class PassGen:
    def __init__(self):
        password = []

        self.vowel_list = lists.vowel_list
        self.consonant_list = lists.consonant_list
        self.number_list = lists.number_list
        self.symbol_list = lists.symbol_list
        #self.characters = characters
        chars = str(input("How many characters do you want?\n"))
        for i in range(int(chars)):
            for i in range(len(chars)):
                password += self.vowel_list[random.randint(0, len(self.vowel_list))]
                password += self.consonant_list[random.randint(0, len(self.consonant_list))]
                password += self.symbol_list[random.randint(0, len(self.symbol_list))]
                password += self.number_list[random.randint(0, len(self.number_list))]

        print(len(chars))
        end_pass = ""
        for i in password:
            end_pass += i
        print(str(end_pass))

def main():
    #characters = str(input("How many characters do you want your password to be?\n"))
    passWord = PassGen()


if __name__ == "__main__":
    main()
如前所述,randint的上限是包含在内的。这意味着randint1,3将随机返回数字1,2和3

random.randint(0, len(self.vowel_list))
将随机返回0到lenself.votel_列表中的数字;包含全部费用但问题是lenself.元音列表超出了列表元音列表的范围。如果该列表有3个元素,则该列表中没有索引3。最高索引为2,因为索引从0开始

您需要从上限中减去一,以确保索引保持在边界内:

password += self.vowel_list[random.randint(0, len(self.vowel_list) - 1)]
或者使用变体:


请提供完整的回溯。请注意,randint可以返回与上限相等的数字。上限不是唯一的。我试图创建一个非常简单的密码生成器应用程序,仍然不明白为什么列表索引超出范围错误存在
password += self.vowel_list[random.randrange(0, len(self.vowel_list))]