【Python 基础】列表中的元素排序例子
返回: Python基础 索引页
假设有一个如下的列表:
mylist = [3, 5, 2, 1, 8, 4]
我希望对其进行排序,达成排序后变成 [1,2,3,4,5,8]。
代码例子如下:
mylist = [3, 5, 2, 1, 8, 4] tester=0 lcount = len(mylist) for x in range(lcount-1): for y in range(x+1,lcount): print("") print ("x is: " + str (x) + " y is: " + str(y) ) print ("mylist[x] is: " + str ( mylist[x] ) + " mylist[y] is: " + str ( mylist[y] ) ) print(mylist) ## if mylist[x]>mylist[y]: mylist[x],mylist[y]=mylist[y],mylist[x] print("exchanged") else: tester=1 ## Just to make if-else to end easily print(mylist) tester=0 ## Just to make the outer for cycle to end easily print (mylist)
运行的结果,展示了每一次排序动作前后的变化:
x is: 0 y is: 1 mylist[x] is: 3 mylist[y] is: 5 [3, 5, 2, 1, 8, 4] [3, 5, 2, 1, 8, 4] x is: 0 y is: 2 mylist[x] is: 3 mylist[y] is: 2 [3, 5, 2, 1, 8, 4] exchanged [2, 5, 3, 1, 8, 4] x is: 0 y is: 3 mylist[x] is: 2 mylist[y] is: 1 [2, 5, 3, 1, 8, 4] exchanged [1, 5, 3, 2, 8, 4] x is: 0 y is: 4 mylist[x] is: 1 mylist[y] is: 8 [1, 5, 3, 2, 8, 4] [1, 5, 3, 2, 8, 4] x is: 0 y is: 5 mylist[x] is: 1 mylist[y] is: 4 [1, 5, 3, 2, 8, 4] [1, 5, 3, 2, 8, 4] x is: 1 y is: 2 mylist[x] is: 5 mylist[y] is: 3 [1, 5, 3, 2, 8, 4] exchanged [1, 3, 5, 2, 8, 4] x is: 1 y is: 3 mylist[x] is: 3 mylist[y] is: 2 [1, 3, 5, 2, 8, 4] exchanged [1, 2, 5, 3, 8, 4] x is: 1 y is: 4 mylist[x] is: 2 mylist[y] is: 8 [1, 2, 5, 3, 8, 4] [1, 2, 5, 3, 8, 4] x is: 1 y is: 5 mylist[x] is: 2 mylist[y] is: 4 [1, 2, 5, 3, 8, 4] [1, 2, 5, 3, 8, 4] x is: 2 y is: 3 mylist[x] is: 5 mylist[y] is: 3 [1, 2, 5, 3, 8, 4] exchanged [1, 2, 3, 5, 8, 4] x is: 2 y is: 4 mylist[x] is: 3 mylist[y] is: 8 [1, 2, 3, 5, 8, 4] [1, 2, 3, 5, 8, 4] x is: 2 y is: 5 mylist[x] is: 3 mylist[y] is: 4 [1, 2, 3, 5, 8, 4] [1, 2, 3, 5, 8, 4] x is: 3 y is: 4 mylist[x] is: 5 mylist[y] is: 8 [1, 2, 3, 5, 8, 4] [1, 2, 3, 5, 8, 4] x is: 3 y is: 5 mylist[x] is: 5 mylist[y] is: 4 [1, 2, 3, 5, 8, 4] exchanged [1, 2, 3, 4, 8, 5] x is: 4 y is: 5 mylist[x] is: 8 mylist[y] is: 5 [1, 2, 3, 4, 8, 5] exchanged [1, 2, 3, 4, 5, 8] [1, 2, 3, 4, 5, 8] <<<< 最终的结果
返回: Python基础 索引页