循环时避免 Python 中的索引错误
Avoiding an indexing error in Python while looping
无论这是否是在 Python 中构建此排序算法的最有效方法(不是),我对索引 requirements/the 内置 'min' 性质的理解函数无法解释以下代码中的以下错误:
Error:
builtins.IndexError: list index out of range
代码如下:
#Create function to sort arrays with numeric entries in increasing order
def selection_sort(arr):
arruns = arr #pool of unsorted array values, initially the same as 'arr'
indmin = 0 #initialize arbitrary value for indmin.
#indmin is the index of the minimum value of the entries in arruns
for i in range(0,len(arr)):
if i > 0: #after the first looping cycle
del arruns[indmin] #remove the entry that has been properly sorted
#from the pool of unsorted values.
while arr[i] != min(arruns):
indmin = arruns.index(min(arruns)) #get index of min value in arruns
arr[i] = arruns[indmin]
#example case
x = [1,0,5,4] #simple array to be sorted
selection_sort(x)
print(x) #The expectation is: [0,1,4,5]
我查看了其他几个索引错误示例,但无法将我的问题归因于 entering/exiting 我的 while 循环时发生的任何事情。我认为我的排序过程映射是合理的,但我的代码甚至在上面分配给 x 的简单数组上失败。如果可以请帮忙。
arr
和 arruns
是相同的列表。您正在从列表中删除项目,减小其大小,但保持 i
变量的最大值不变。
修复:
arruns = [] + arr
这将为 arruns
创建新数组
无论这是否是在 Python 中构建此排序算法的最有效方法(不是),我对索引 requirements/the 内置 'min' 性质的理解函数无法解释以下代码中的以下错误:
Error: builtins.IndexError: list index out of range
代码如下:
#Create function to sort arrays with numeric entries in increasing order
def selection_sort(arr):
arruns = arr #pool of unsorted array values, initially the same as 'arr'
indmin = 0 #initialize arbitrary value for indmin.
#indmin is the index of the minimum value of the entries in arruns
for i in range(0,len(arr)):
if i > 0: #after the first looping cycle
del arruns[indmin] #remove the entry that has been properly sorted
#from the pool of unsorted values.
while arr[i] != min(arruns):
indmin = arruns.index(min(arruns)) #get index of min value in arruns
arr[i] = arruns[indmin]
#example case
x = [1,0,5,4] #simple array to be sorted
selection_sort(x)
print(x) #The expectation is: [0,1,4,5]
我查看了其他几个索引错误示例,但无法将我的问题归因于 entering/exiting 我的 while 循环时发生的任何事情。我认为我的排序过程映射是合理的,但我的代码甚至在上面分配给 x 的简单数组上失败。如果可以请帮忙。
arr
和 arruns
是相同的列表。您正在从列表中删除项目,减小其大小,但保持 i
变量的最大值不变。
修复:
arruns = [] + arr
这将为 arruns