在Python中,如何使用while循环对列表进行排序?
如何使用while循环对列表进行排序?有点问题,非常感谢在Python中,如何使用while循环对列表进行排序?,python,computer-science,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) a=[12,0,39,50,1] 第一个=a[0] i=0 j=1 而我
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)
a=[12,0,39,50,1]
第一个=a[0]
i=0
j=1
而我
以下是使用两个while循环实现基本排序。
在每次迭代中,从未排序的子数组中选取最小元素(考虑升序),并将其移动到已排序的子数组中。
:
a=[12,0,39,50,1]
i=0
当i时,您还可以使用以下示例连接两个列表并按降序/升序对它们进行排序:
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))
x=[2,9,4,6]
y=[7,8,3,5]
z=[]
maxi=x[0]
pos=0
打印('x:'+str(x))
打印('y:'+str(y))
对于范围内的i(len(y)):
x、 附加(y[i])
对于范围内的j(透镜(x)-1):
maxi=x[0]
对于范围内的i(len(x)):
如果maxi
您可以创建一个空列表来存储排序后的数字
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)
a=[12,0,39,50,1]
kk=len(a)
新的_a=[]
i=0
而我
请注意,我在while语句中使用了列表a(kk)的原始长度,以便不停止迭代,因为列表a的长度随着我们删除最小数而减少。最简单的排序算法之一是插入排序;查找示例实现或解释这不是作者想要的。
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)