1. 程式人生 > >Python基礎---數列排序(for迴圈 list)

Python基礎---數列排序(for迴圈 list)

def sortlist(numberlist):
    n = 1 #計數交換次數
    m = 0 #計數交換時對應的列表位置
    for i in range(len(numberlist)):
        for j in range(len(numberlist)):
            if numberlist[i] >= numberlist[j]:
                print("第{0}次比較:".format(n)) #新增比較次數
                temp = numberlist[i]
                print("number[{0}] = {1}".format(m,numberlist[m]))
                numberlist[i] = numberlist[j]#交換位置
                print("第{0}次交換".format(n))
                print("number[{0}] = {1}".format(m,numberlist[m]))
                print("交換後數列:",numberlist)
                numberlist[j] = temp       #賦予較大數
                print("交換後原數列變為:",numberlist)
            n += 1
        m += 1
    return numberlist                
numberlist = [1,2,3]                 
print(sortlist(numberlist))

逐個比較,將較大的數交換前置,
列表從大到小排序.

def sortlist1(glist):
	'''
	glist = 原始列表
	'''
	newlist = []
	while len(glist) > 0:
    	newlist.append([max([n for n in glist])])  #向新列表中插入最大值 max/min
    	glist.remove(max(glist))                          #從原始列表中刪除最大值
    	return newlist                                          #返回新生成的列表
 print(newlist)