Python 似乎自动匹配两个列表,阻止我将它们分开

Python seems to be automatically matching two lists, preventing me from separating them

# arranges a lists indexes from which ones have the maximum 
# value to which ones have the minimum value
def sortIndex(L):
  I = []
  original = L
  new = L
  for i in range(len(original)):
    I.append(original.index(max(new)))
    del new[I[len(I)-1]]
    print("I=",I)
    print("O=",original)
    print("N=",new)
  return I

A = [1,6,3,8,4]

print(sortIndex(A)) 

这就是代码。当我 运行 它时,我得到输出(注意我在每次迭代后打印 I、O 和 N):

  I= [3]
  O= [1, 6, 3, 4]
  N= [1, 6, 3, 4]
  I= [3, 1]
  O= [1, 3, 4]
  N= [1, 3, 4]
  I= [3, 1, 2]
  O= [1, 3]
  N= [1, 3]
  I= [3, 1, 2, 1]
  O= [1]
  N= [1]
  I= [3, 1, 2, 1, 0]
  O= []
  N= []
  [3, 1, 2, 1, 0]  

我不明白为什么会这样。 Del 似乎正在删除新值和原始值,即使它们显然是分开的列表。有人知道这里发生了什么吗?

因为它们实际上并不是单独的列表。 neworiginal 这两个变量都指向内存中的同一个列表。您可以使用 copy.deepcopy

创建您想要的副本
from copy import deepcopy
original = L
new=deepcopy(original)