【问题标题】:Python throws a List Index Out Of Range ErrorPython 抛出列表索引超出范围错误
【发布时间】:2019-09-13 21:18:22
【问题描述】:

我尝试了列表理解,但显然我失败了。有人可以帮忙吗?

我在 Windows 10 上使用 python 3.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 可以返回等于上限的数字。上限不是排他性的。
  • 我正在尝试创建一个非常简单的密码生成器应用程序,但仍然不明白为什么会出现列表索引超出范围错误

标签: python list for-loop list-comprehension


【解决方案1】:

randint 的上限包括在内,如 in the docs 所述。这意味着randint(1, 3) 将随机返回数字 1、2 和 3。

random.randint(0, len(self.vowel_list))

会随机返回0到len(self.vowel_list)之间的数字;包括的。但问题是len(self.vowel_list) 超出了列表vowel_list 的范围。如果该列表有 3 个元素,则该列表中没有索引 3。最高索引为 2(因为索引从 0 开始)。

您需要从上限中减去一个以确保索引保持在范围内:

password += self.vowel_list[random.randint(0, len(self.vowel_list) - 1)]

或使用randrange 变体:

password += self.vowel_list[random.randrange(0, len(self.vowel_list))]

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2016-01-06
    • 2014-11-03
    • 1970-01-01
    相关资源
    最近更新 更多