如何在Python中使用while循环对列表进行排序?

时间:2017-05-05 16:24:25

标签: python computer-science

如何使用while循环对列表进行排序?有一点问题,非常感谢。

a = [12,0,39,50,1]

first = a[0]

i = 0
j = 1
while i < len(a):
    if a[i] < first:
        tmp = a[i]
        a[i] = a[j]
        a[j] = tmp
    i += 1

print(a)

3 个答案:

答案 0 :(得分:0)

以下是使用两个while循环实现基本排序。 在每次迭代中,挑选来自未排序子阵列的最小元素(考虑升序)并将其移动到排序的子阵列。 :

a=[12,0,39,50,1]
i=0
while i<len(a):
    key=i
    j=i+1
    while j<len(a):
        if a[key]>a[j]:
            key=j
        j+=1
    a[i],a[key]=a[key],a[i]
    i+=1
print(a)

答案 1 :(得分:0)

您可以创建一个空列表来存储您的已排序数字

a     = [12,0,39,50,1]
kk    = len(a)
new_a = []
i     = 0

while i < kk:
    xx = min(a)      ## This would retreive the minimum value from the list (a)
    new_a.append(xx) ## You store this minimum number in your new list (new_a)
    a.remove(xx)     ## Now you have to delete that minimum number from the list a
    i += 1           ## This starts the whole process again.
print(new_a)

请注意,我在while语句中使用了列表a(kk)的原始长度,以免停止迭代,因为删除最小数时列表a的长度会减小。

答案 2 :(得分:-1)

您还可以使用此示例连接两个列表并按递减/递增顺序对它们进行排序:

x = [2,9,4,6]
y = [7,8,3,5]
z = []
maxi = x[0]
pos = 0
print('x: '+str(x))
print('y: '+str(y))

for i in range(len(y)):
  x.append(y[i])

for j in range(len(x)-1):
    maxi = x[0]
    for i in range(len(x)):
        if maxi < x[i]:
            maxi = x[i]
            pos = i
    z.append(maxi)
    del x[pos]
z.append(x[0])
print('z: '+str(z))