【问题标题】:How do you sort a list with a while loop in Python?如何在 Python 中使用 while 循环对列表进行排序?
【发布时间】:2017-05-05 16:24:24
【问题描述】:

如何使用 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)

【问题讨论】:

  • 最简单的排序算法之一是插入排序;查找示例实现或解释

标签: python computer-science


【解决方案1】:

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

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】:

    以下是使用两个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)
    

    【讨论】:

      【解决方案3】:

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

      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))
      

      【讨论】:

      • 这不是作者要求的。
      猜你喜欢
      • 2021-12-10
      • 2017-05-26
      • 2018-01-31
      • 2022-06-14
      • 2013-10-30
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      相关资源
      最近更新 更多