Python 在同时添加值时执行插入排序时出现问题
我制作了一个程序,同时从一个列表和一个元组中提取元素{即从列表中提取一个元素,然后从元组中提取一个元素,然后从列表中提取一个元素,依此类推},然后将它们放在一个新的列表中,并在插入时使用插入排序对它们进行排序。我面临的问题是数字排序不正确 我得到的输出[8,6,9,4,3,1,2,5,7] 我想要的输出。[1,2,3,4,5,6,7,8,9]Python 在同时添加值时执行插入排序时出现问题,python,sorting,Python,Sorting,我制作了一个程序,同时从一个列表和一个元组中提取元素{即从列表中提取一个元素,然后从元组中提取一个元素,然后从列表中提取一个元素,依此类推},然后将它们放在一个新的列表中,并在插入时使用插入排序对它们进行排序。我面临的问题是数字排序不正确 我得到的输出[8,6,9,4,3,1,2,5,7] 我想要的输出。[1,2,3,4,5,6,7,8,9] list = [8,6,4,2] tuple = (9,5,7,1,3) final = [list[0],] # creating a final l
list = [8,6,4,2]
tuple = (9,5,7,1,3)
final = [list[0],] # creating a final list with the value list[0]
list.pop(0) # removing the first element from list
l = len(list)
t = len(tuple)
# now comparing whoes length is greater and assigning it to j
if l > t:
j = l
else:
j = t
b = 0 # variable to keep the count of elements in the final list starting from 0 to n-1
for i in range(j):
n = b
if i < l: # Making sure the index dosen't exceed the list
temp = list[i]
final.append(temp) # appending the value to last
while temp < final[n] & n>-1:
final[n+1] = final[n]
n = n-1
final[n+1] = temp
b+=1 # a value is added to final list so the total no of elements increases
n=b
if i < t: # Making sure the index dosen't exceed the tuple
temp = tuple[i]
final.append(temp)
while temp < final[n] & n>-1:
final[n+1] = final[n]
n = n-1
final[n+1] = temp
b+=1
print(final)
list=[8,6,4,2]
元组=(9,5,7,1,3)
final=[list[0],]#使用值列表[0]创建最终列表
list.pop(0)#从列表中删除第一个元素
l=len(列表)
t=len(元组)
#现在比较谁的长度更大,并将其分配给j
如果l>t:
j=l
其他:
j=t
b=0#变量,用于将最终列表中的元素计数保持在从0到n-1之间
对于范围(j)内的i:
n=b
如果i-1时:
最终[n+1]=最终[n]
n=n-1
最终[n+1]=温度
b+=1#一个值被添加到最终列表中,因此元素总数增加
n=b
如果i-1时:
最终[n+1]=最终[n]
n=n-1
最终[n+1]=温度
b+=1
打印(最终版)
您可以使用.sort()
方法获得正确的顺序
...
b+=1
final.sort()
print(final)
我不允许使用排序功能