python 追加问题,函数不断改变列表的值

python appending issues, function keeps changing values of list

我试图通过在一些未排序的列表上制作动画图来可视化冒泡排序,比如 np.random.permutation(10)

所以每次在 bubblesort 函数中更改列表时,我自然会附加列表,直到它完全排序。这是代码

def bubblesort(A):
  instant = []

  for i in range(len(A)-1):
    lindex=0
    while lindex+1<len(A):
      if A[lindex]> A[lindex+1]:
        swap(A,lindex,lindex+1)
        lindex+=1
      else:
        lindex+=1   

      instant.append(A)
  return instant

问题是,instant 只有 returns

[array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])]

这显然是不对的。出了什么问题?谢谢!

A 正在就地操作,bubblesort 正在返回对该数组的引用列表。请注意,如果您现在检查 A,它也会被排序。

改变

  if A[lindex]> A[lindex+1]:
      swap(A,lindex,lindex+1)

  if A[lindex]> A[lindex+1]:
      A = A.copy()
      swap(A,lindex,lindex+1)

在更改任何内容之前制作副本,应该显示排序的进度。