【问题标题】:Why do the two following lines of code give different results? [duplicate]为什么以下两行代码给出不同的结果? [复制]
【发布时间】: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


【解决方案1】:

已在 cmets 中回答。另外,这应该可以解决问题。

def combinations(n):
   if len(n) == 1:
       return [[], n]
   a = list(n)
   a.pop(0)
   return [[n[0]] + comb for comb in combinations(a)] + combinations(a)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-15
    • 2021-08-31
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多