小编典典

Python:为什么在我实际上不更改列表时会更改它?

python

新手有问题,请保持温柔:

list = [1, 2, 3, 4, 5]
list2 = list

def fxn(list,list2):
    for number in list:
        print(number)
        print(list)
        list2.remove(number)
        print("after remove list is  ", list, " and list 2 is  ", list2)
    return list, list2

list, list2 = fxn(list, list2)
print("after fxn list is  ", list)
print("after fxn list2 is  ", list2)

结果是:

1
[1, 2, 3, 4, 5]
after remove list is   [2, 3, 4, 5]  and list 2 is   [2, 3, 4, 5]
3
[2, 3, 4, 5]
after remove list is   [2, 4, 5]  and list 2 is   [2, 4, 5]
5
[2, 4, 5]
after remove list is   [2, 4]  and list 2 is   [2, 4]
after fxn list is   [2, 4]
after fxn list2 is   [2, 4]

我不明白为什么列表改变时,我只是在做list2.remove(),没有list.remove()。我什至不知道要用什么搜索词来弄清楚。


阅读 179

收藏
2020-12-20

共1个答案

小编典典

这是因为在进行分配后,listlist2都引用相同的列表list2=list

尝试执行以下操作以查看它们是指相同的对象还是不同的对象:

id(list)
id(list2)

一个例子:

>>> list = [1, 2, 3, 4, 5]
>>> list2 = list
>>> id(list)
140496700844944
>>> id(list2)
140496700844944
>>> list.remove(3)
>>> list
[1, 2, 4, 5]
>>> list2
[1, 2, 4, 5]

如果您确实要创建这样的重复副本,listlist2不是引用原始列表,而是引用列表的副本,请使用slice运算符:

list2 = list[:]

一个例子:

>>> list
[1, 2, 4, 5]
>>> list2
[1, 2, 4, 5]
>>> list = [1, 2, 3, 4, 5]
>>> list2 = list[:]
>>> id(list)
140496701034792
>>> id(list2)
140496701034864
>>> list.remove(3)
>>> list
[1, 2, 4, 5]
>>> list2
[1, 2, 3, 4, 5]

另外,请勿将其list用作变量名,因为最初list是指类型列表,但是通过定义自己的list变量,您将隐藏list引用类型列表的原始变量。例:

>>> list
<type 'list'>
>>> type(list)
<type 'type'>
>>> list = [1, 2, 3, 4, 5]
>>> list
[1, 2, 3, 4, 5]
>>> type(list)
<type 'list'>
2020-12-20