Python 为什么有时会出现索引错误,但有时不会?
我有一个索引错误,但我不知道为什么Python 为什么有时会出现索引错误,但有时不会?,python,jupyter-notebook,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 = rando
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])
随机函数在包含的第一个和最后一个数字之间生成一个数字。所以它也可以是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)
随机函数在包含的第一个和最后一个数字之间生成一个数字。所以它也可以是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)
python
random.randint(a,b)
返回一个数字apythonrandom.randint(a,b)
返回一个数字a Trylen(tmpList)-1
Trylen(tmpList)-1
解决方案是什么?@Selcuk正确使用randint;)(又称不越界)解决方案是什么?@Selcuk正确使用randint;)(又称不越界)