Skip to content

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]]
  1. We call b1 an alias of a, since they are just different names for the same list.
  2. We call b2 a shallow-copy of a, which means b2 is not a, but the contents of b2 are the same objects as the contents of a.
  3. We call b3 a deep-copy of a, as all the contents of b3 (i.e., lists of integers) are created via slicing and are not the same objects as the contents of a.

Now you need to implement a function deep to 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.

  1. 我们称 b1a别名(alias),因为它们只是同一列表的不同名称。
  2. 我们称 b2a浅拷贝(shallow-copy),这意味着 b2 不是 a,但 b2 的内容(即其中的元素)与 a 的内容是相同的对象
  3. 我们称 b3a深拷贝(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]