在python中复制可变列表

luz*_*zik -1 python mutable

如何不更改列表的值???

>>> a=range(0,5)
>>> b=10
>>> c=a
>>> c.append(b)
>>> c
[0, 1, 2, 3, 4, 10]
>>> a
[0, 1, 2, 3, 4, 10]
Run Code Online (Sandbox Code Playgroud)

直到今天我还不知道python中的列表是可变的!

fal*_*tru 7

Followng语句c引用相同列表a引用.

c = a
Run Code Online (Sandbox Code Playgroud)

要制作(浅)副本,请使用切片表示法:

c = a[:]
Run Code Online (Sandbox Code Playgroud)

或使用copy.copy:

import copy

c = copy.copy(a)
Run Code Online (Sandbox Code Playgroud)
>>> a = range(5)
>>> c = a[:]  # <-- make a copy
>>> c.append(10)
>>> a
[0, 1, 2, 3, 4]
>>> c
[0, 1, 2, 3, 4, 10]
>>> a is c
False
>>> c = a    # <--- make `c` reference the same list
>>> a is c
True
Run Code Online (Sandbox Code Playgroud)