Python代码执行偶发IndexError: list index out of range错误的原因是什么?
为什么这段代码会抛出IndexError: list index out of range?
咱们来拆解下你遇到的问题:
你的代码里用了random.randint(0, len(list1)),这里的关键是**randint(a, b)会返回一个介于a和b之间的整数,而且是包含a和b两个端点的**。
看你的list1,它的长度是5,对应的有效索引是0、1、2、3、4(因为Python列表是从0开始计数的)。但len(list1)返回的是5,所以randint(0,5)可能会生成0到5之间的任意整数——包括5。
当随机数抽到5的时候,你去访问list1[5]或者list2[5],自然就会触发IndexError,因为这两个列表根本没有索引为5的元素。
怎么修复?
很简单,有两种常用的解决思路:
- 把
randint的上限改成len(list1)-1,确保生成的索引在有效范围内 - 用
random.randrange(len(list1)),它的上限是不包含的,默认从0开始,刚好匹配列表的索引范围
举个修复后的例子:
import random list1 = ['afgdddd', 'bcbvnbn', 'casretb', 'dbcbv ', 'egfhsgs'] list2 = ['a5y5546', 'brtewtwret', 'chrtyey', 'dqawtet', 'egreg'] choice1 = random.randint(0, len(list1)-1) # 限制上限为有效最大索引 print(list1[choice1]) print(list2[choice1])
或者用更简洁的randrange写法:
choice1 = random.randrange(len(list1))
这样就不会再出现索引越界的问题啦。
内容的提问来源于stack exchange,提问作者Airstorm 3822
相关产品推荐
相关产品推荐

