在python列表中实现升序排序 [英] Implement ascending sort in a python list
本文介绍了在python列表中实现升序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为python分配的一部分,我试图在不使用 sort()方法的情况下实现列表排序(升序),我认为我的逻辑是正确的,但是我一直遇到错误:>
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=0
for 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
推荐答案
对此进行检查: python气泡排序:
python bubble sorting:
sample=[23,44,12,1,6,87]
sorted = False
while 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列表中实现升序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文