【发布时间】:2021-10-14 04:09:48
【问题描述】:
我想构建一个函数来查找集合的所有可能子集。 第一个功能运行良好,而第二个则不行。在第一个中,我使用列表推导来删除列表的第一个元素,而在第二个中,我使用了 pop(0)。为什么他们输出不同的结果? 第一个函数是:
def combinations(n):
if len(n) == 1:
return [[], n]
a = [element for element in n if element != n[0]]
return [[n[0]] + comb for comb in combinations(a)] + combinations(a)
第二个功能是:
def combinations(n):
if len(n) == 1:
return [[], n]
a = n
a.pop(0)
return [[n[0]] + comb for comb in combinations(a)] + combinations(a)
第一个的输出是:
[[0, 1, 2], [0, 1, 2, 3], [0, 1], [0, 1, 3], [0, 2], [0, 2, 3], [0], [0, 3], [1, 2], [1, 2, 3], [1], [1, 3], [2], [2, 3], [], [3]]
第二个的输出是:
[[3, 3, 3], [3, 3, 3, 3], [3, 3], [3, 3, 3], [3], [3, 3], [], [3]]
【问题讨论】:
-
请注意,
a = n不会进行复制。这是同一个列表的两个名称。不过,第一个代码中的列表推导确实会生成n的过滤副本。 -
感谢您的回答。所以基本上,我只是指同一个列表,但名称不同?
-
是的。 Python 不会在分配时为您制作副本。 This 将是一个很好的阅读。
a = n只是创建第二个标签a,它指向与n相同的列表。您可以通过print(id(a), id(n))看到这一点。它们指向相同的内存位置。
标签: python