As part of a python assignment I'm trying to implement list sorting (ascending) without using the sort() method, I think my logic is correct but I keep getting an error:sample=[23,44,12,1,6,87]temp=0for i in range(0,len(sample)): if sample[i] > sample[i+1]: sample[i]=temp sample[i]=sample[i+1] sample[i+1]=temp这一直给我一个列表:索引超出范围错误,我知道这是由于以下事实引起的:当i == 3时,代码仍会执行i + 1.This keeps giving me a list: index out of range error which I know is being caused by the fact that when the i == 3 the code still does i+1.需要帮助..我将代码更改为:for i in range(0,len(sample)-1): if sample[i] > sample[i+1]: temp=sample[i] sample[i]=sample[i+1] sample[i+1]=temp消除了错误但不对列表进行排序that eliminates the error but doesn't sort the list推荐答案对此进行检查: http://faculty.cs.niu.edu/~hutchins/csci241/sorting.htm python气泡排序:python bubble sorting:sample=[23,44,12,1,6,87]sorted = Falsewhile not sorted: sorted = True for i in range(len(sample) - 1): if sample[i] > sample[i+1]: sorted = False sample[i], sample[i+1] = sample[i+1], sample[i]print sample从此处更改:气泡排序作业 这篇关于在python列表中实现升序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-27 11:07