xxx*_*--- 4 python nested-lists python-2.7
我正在研究这些功能(见这个):
def removeFromList(elementsToRemove):
def closure(list):
for element in elementsToRemove:
if list[0] != element:
return
else:
list.pop(0)
return closure
def func(listOfLists):
result = []
for i, thisList in enumerate(listOfLists):
result.append(thisList)
map(removeFromList(thisList), listOfLists[i+1:])
return result
Run Code Online (Sandbox Code Playgroud)
我有一个列表,我想作为参数传递,但我希望这个列表保持不变.我尝试的是:
my_list = [[1], [1, 2], [1, 2, 3]]
print my_list
#[[1], [1, 2], [1, 2, 3]]
copy_my_list = list (my_list)
#This also fails
#copy_my_list = my_list [:]
print id (my_list) == id (copy_my_list)
#False
print func (copy_my_list)
#[[1], [2], [3]]
print my_list
#[[1], [2], [3]]
Run Code Online (Sandbox Code Playgroud)
但它确实改变了我的原始列表.有任何想法吗?
用途copy.deepcopy:
from copy import deepcopy
new_list = deepcopy([[1], [1, 2], [1, 2, 3]])
Run Code Online (Sandbox Code Playgroud)
演示:
>>> lis = [[1], [1, 2], [1, 2, 3]]
>>> new_lis = lis[:] # creates a shallow copy
>>> [id(x)==id(y) for x,y in zip(lis,new_lis)]
[True, True, True] #inner lists are still the same object
>>> new_lis1 = deepcopy(lis) # create a deep copy
>>> [id(x)==id(y) for x,y in zip(lis,new_lis1)]
[False, False, False] #inner lists are now different object
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |