python列表内容排序

需求,有一个数字列表,我们需要按照大小排序:

a = [103,22,456,100,482,321]

排序的结果是:[22, 100, 103, 321, 456, 482]

#排序#
a = [103,22,456,100,482,321]
count = 1
while count < len(a):
    
    for i in range(0,len(a)-1):
        temp1 = a[i]
        temp2 = a[i+1]

        if a[i] > a[i+1]:
            a[i] = temp2
            a[i+1] = temp1
    count+=1
print(a)

核心思想就是:相邻的两个数字比大小,a[i] > a[i+1],如果左边的数字比右边大,则需要调换两个数字的位置,这样遍历一次,最大的数字就放在了最右,所以使用while循环对列表同样操作len(list)-1次,就能得到排序结果了。

你可能感兴趣的:(python列表操作)