Python。发生异常:IndexError。列表索引超出范围

时间:2021-04-02 10:41:06

标签: python

<块引用>

发生异常:IndexError list index out of range File “C:\Pyprojects\isPhoneNumber.py”,第 11 行,在 findSmallest 中 最小 = lis[0] 文件“C:\Pyprojects\isPhoneNumber.py”,第 44 行,在 indexOfTheSmallest = findSmallest(lis)

import random

lis = []

for r in range(10):
    lis.append(random.randint(1, 60))


def findSmallest(lis):
    """ Finds the smallest number index in a list. """
    smallest = lis[0]
    smallest_index = 0
    for i in range(1, len(lis)):
        if lis[i] < smallest:
            smallest = lis[i]
            smallest_index = i
    return smallest_index


def findBiggest(lis):
    """ FInd the biggest number index in a list. """
    biggest = lis[0]
    biggest_index = 0
    for i in range(1, len(lis)):
        if lis[i] > biggest:
            biggest = lis[i]
            biggest_index = i
    return biggest_index


def selectionSort(lis):
    """ Selection sort algorithm implementation. """
    newArr = []
    for i in range(len(lis)):
        smallest = findSmallest(lis)
        newArr.append(lis.pop(smallest))
    return newArr


sortedlist = selectionSort(lis)
print(sortedlist)


indexOfTheSmallest = findSmallest(lis)
indexOfTheBiggest = findBiggest(lis)

print("list: " + str(lis))
print("the biggest number index: " + str(indexOfTheBiggest))
print("the smallest number index: " + str(indexOfTheSmallest))

2 个答案:

答案 0 :(得分:2)

您的 selectionSort 会改变它给定的参数(pop 在它发生时关闭元素)。当 sortedlist = selectionSort(lis) 完成时,lis 为空,因此 indexOfTheSmallest = findSmallest(lis) 被传递一个空的 list,并在尝试索引元素 0 时死亡(根本没有元素).

如果您希望使 selectionSort 不发生变异,请在接收参数时复制参数,例如

def selectionSort(lis):
    """ Selection sort algorithm implementation. """
    lis = list(lis)  # Make copy to avoid mutating caller; explicit conversion to list means
                     # non-list iterables accepted too, like sorted built-in
    newArr = []
    for i in range(len(lis)):
        smallest = findSmallest(lis)
        newArr.append(lis.pop(smallest))
    return newArr

答案 1 :(得分:1)

您的排序函数调用 pop(index) 因此 lis 在该行之后变为空

sortedlist = selectionSort(lis)

然后您尝试在空列表中查找最小元素的索引,当您尝试通过 smallest = lis[0] 获取第一个元素时会导致异常。