【问题标题】:list index out of range while list is full列表已满时列表索引超出范围
【发布时间】:2018-01-25 15:11:25
【问题描述】:

当我执行这段代码时:

import random
list1 = ['afgdddd', 'bcbvnbn', 'casretb', 'dbcbv ', 'egfhsgs']
list2 = ['a5y5546', 'brtewtwret', 'chrtyey', 'dqawtet', 'egreg']
choice1 = random.randint(0, len(list1))
print(list1[choice1])
print(list2[choice1])

有时会出现这个错误:

python IndexError: 列表索引超出范围

这是什么原因造成的?

【问题讨论】:

    标签: python-3.x list indexing


    【解决方案1】:

    长度为 5 的列表的有效列表索引是 0,1,2,3,4。您正在从 0、1、2、3、4、5 中选择一个随机数。当随机数为 5 时,正如错误消息所述,您的索引超出范围。

    为防止这种情况发生,您需要一个介于 0 和 4 之间的随机数。只需更改为:

    choice1 = random.randint(0, len(list1) - 1)
    

    从列表的长度中减去 1 是获取数组中最后一个元素的一种非常常见的模式。

    要自己调试类似的东西,您应该先print(choice1),然后再尝试print(list1[choice1]),看看为什么索引可能超出范围。

    【讨论】:

    • 有什么办法可以防止这个错误的发生吗?
    • 我将使用的列表长度完全相同。
    猜你喜欢
    • 1970-01-01
    • 2018-12-16
    • 2011-06-14
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多