Python 为什么在这个Insertionsort实现的while循环中需要一个新变量?

Python 为什么在这个Insertionsort实现的while循环中需要一个新变量?,python,insertion-sort,Python,Insertion Sort,我有一个Insertionsort算法的实现,在讲座中,while循环之前有一个新的实例变量 def swap(l, i, j): temp = l[i] l[i] = l[j] l[j] = temp def ins_sort(l): for i in range(len(l)): j = i while j > 0 and l[j - 1] > l[j]: swap(l, j - 1, j

我有一个Insertionsort算法的实现,在讲座中,while循环之前有一个新的实例变量

def swap(l, i, j):
    temp = l[i]
    l[i] = l[j]
    l[j] = temp


def ins_sort(l):
    for i in range(len(l)):
        j = i
        while j > 0 and l[j - 1] > l[j]:
            swap(l, j - 1, j)
            j = j - 1


    return l
在我的测试和游戏中,算法在没有它的情况下也能工作,但我不明白,如果没有必要,为什么我需要额外编写一行代码

def swap(l, i, j):
    temp = l[i]
    l[i] = l[j]
    l[j] = temp


def ins_sort(l):
    for i in range(len(l)):
        while i > 0 and l[i - 1] > l[i]:
            swap(l, i - 1, i)
            i = i - 1


    return l

看起来原始代码是c/c++实现的翻译,在c/c++实现中,在循环中修改i将是持久的,并影响循环本身。然而,由于在python中,每次迭代我都会重置,所以第二个代码也可以工作。 简而言之,我认为python实现不需要这一行


ref:

在不需要使用额外变量的情况下,您也可以尝试以下程序进行插入排序:

l=[4,3,1,2]
for i in range(1,len(l)): 
      key=l[i]  
      for j in range(i-1,-1,-1):
          if l[j]>key:
              l[j+1]=l[j]
          else:
              j=j+1
              break

      l[j]=key

print(l)

对于临时值,
swap
功能也是不必要的
l[i],l[j]=l[j],l[i]
应该像作者不懂Python一样做同样的事情。谢谢你的回答和参考,并为我澄清了这一点