-2

I use a list in the argument of the following function:

def myFunct(myList):
  print(myList) # display [0,1]
  myModifiedList = list(myList)
  myModifiedList[0]=-1
  print(myList) # display [-1,1]
  return myModifiedList

Of course, I'd like to display [0,1] at my second print in my function myList. I can't find out what's wrong here, I know that everything in python works by reference. However, my function array_copy should help me to avoid the problem I'm having.

Edit: I deleted the "weird" method, but still having the problem.

4

3 回答 3

3

首先,您的代码打印了[0, 1]两次,并且[0, 1]后面没有[-1, 1]. 这并不是说它完美无瑕。

一个错误是:

for i in array:
   copy.append(array[i])

i迭代列表元素,而不是索引。因此,array[i]应该阅读i

事实上,整个array_copy()函数是不必要的。您可以更换:

myModifiedList = array_copy(myList)

myModifiedList = myList[:]

制作列表的(浅)副本。

于 2013-03-16T15:32:12.337 回答
2

我无法使用复制列表的健全方法重现此行为:

>>> mylist = [0, 1]
>>> modified = list(mylist)
>>> modified[0] = -1
>>> print(mylist)
[0, 1]

您是否实际运行了问题中的代码?正如 NPE 指出的那样,您的复制功能本质上是有缺陷的。与往常一样,最好的答案是不要重新发明轮子,而是使用内置的方法来做这件事。

于 2013-03-16T15:32:06.457 回答
0
>>> a=[0,1]
>>> print a
[0, 1]
>>> b=a
>>> b[0]=-1
>>> print a
[-1, 1]
>>> c=list(a)
>>> c[0]=3
>>> print a
[-1, 1]
>>> print c
[3, 1]
>>> print b
[-1, 1]
>>> 
于 2015-05-07T21:28:52.233 回答