Problem 3: Deep (50pts)
Problem
When nested mutable objects appear, the behavior of your program might be confusing. Consider the example below
当出现嵌套的可变对象时,您的程序行为可能会令人困惑。 请看下面的例子
>>> inner1 = [1, 2, 3]
>>> inner2 = [4, 5, 6]
>>> a = [inner1, inner2]
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b1 = a
>>> b2 = a[:]
>>> b3 = [a[0][:], a[1][:]]
>>> b1 == b2 and b2 == b3 and b1 == b3
True
>>> inner1[0] = 222
>>> b1
[[222, 2, 3], [4, 5, 6]]
>>> b2
[[222, 2, 3], [4, 5, 6]]
>>> b3
[[1, 2, 3], [4, 5, 6]]
- We call
b1an alias ofa, since they are just different names for the same list.- We call
b2a shallow-copy ofa, which meansb2is nota, but the contents ofb2are the same objects as the contents ofa.- We call
b3a deep-copy ofa, as all the contents ofb3(i.e., lists of integers) are created via slicing and are not the same objects as the contents ofa.Now you need to implement a function
deepto create a deep-copy of a given non-empty list, whose contents are non-empty lists of integers. In the real-world, objects may be arbitrarily nested (e.g., lists of lists of lists of ...), but in this problem, you only need to handle a simple situation, where the contents of the given list are only lists of integers.
- 我们称
b1为a的别名(alias),因为它们只是同一列表的不同名称。 - 我们称
b2为a的浅拷贝(shallow-copy),这意味着b2不是a,但b2的内容(即其中的元素)与a的内容是相同的对象。 - 我们称
b3为a的深拷贝(deep-copy),因为b3的所有内容(即那些整数列表)都是通过切片创建的,与a的内容不是相同的对象。
现在您需要实现一个函数 deep,它为给定非空列表创建一个深拷贝,该列表的内容是非空的整数列表。
在实际应用中,对象可能存在任意嵌套(例如,列表中的列表中的列表...),但在本问题中,您只需要处理一种简单的情况:给定列表的内容仅为整数列表。
def deep(l):
"""Returns a deep-copy of the given list of lists.
>>> a = [[2, 2, 2], [5, 0, 2], [5, 0, 3]]
>>> b = deep(a)
>>> b
[[2, 2, 2], [5, 0, 2], [5, 0, 3]]
>>> a is b
False
>>> a[0] is b[0]
False
>>> a[1] is b[1]
False
>>> a[2] is b[2]
False
>>> len(a) == len(b)
True
"""
"*** YOUR CODE HERE ***"
Hints
Hint: try to use list comprehension to make your answer concise
-
尝试使用列表推导式(list comprehension)来使您的答案简洁。
-
可以直接用
copy.deepcopy()偷鸡()
Solutions
直接偷鸡
def deep(l):
import copy
return copy.deepcopy(l)
切片可以创建一个新的 list。
def deep(l):
return [x[:] for x in l]