为什么有时会出现索引错误,但有时却没有呢?

时间:2019-04-03 04:42:00

标签: python jupyter-notebook

我遇到了索引错误,但我不知道为什么。

import random

list1=[1,2]
list2=[[1,2], [1,3], [1,4], [2,1], [2,2]]

result = []

for i in list1:
    tmpList = []
    for j in list2:
        if j[0] == i:
            tmpList.append(j)
    if len(tmpList)> 0:
        k = random.randint(0, len(tmpList))
        result.append(tmpList[k])

print(result)

这段代码有时可以给我结果,但有时可以给我

"IndexError: list index out of range" on 
---> 15         result.append(tmpList[k])

2 个答案:

答案 0 :(得分:1)

随机函数会在第一个和最后一个都包含的数字之间生成一个数字。因此它也可以是len(tmpList)。如果随机函数生成最大可能值,则任何列表中只有len(list)-1个索引,因此索引超出范围。因此,在这种情况下,您会得到一个错误。

要解决该问题,请执行以下操作:

import random

list1=[1,2]
list2=[[1,2], [1,3], [1,4], [2,1], [2,2]]

result = []

for i in list1:
    tmpList = []
    for j in list2:
        if j[0] == i:
            tmpList.append(j)
    if len(tmpList)> 0:
        k = random.randint(0, len(tmpList)-1)
        result.append(tmpList[k])

print(result)

答案 1 :(得分:1)

python random.randint( a, b ) function返回数字a <= N <= b

因此有时返回的k等于len(tmpList),而tmpList只能被索引为0-> len(tmpList)-1

尝试:

k = random.randint(0, len(tmpList)-1)
result.append(tmpList[k])