当前位置: 代码迷 >> python >> 在递归函数中添加带有列表的空列表 + []什么作用? 我为什么需要这个? 如果删除+ []为什么它返回空白列表?
  详细解决方案

在递归函数中添加带有列表的空列表 + []什么作用? 我为什么需要这个? 如果删除+ []为什么它返回空白列表?

热度:57   发布时间:2023-06-27 21:49:10.0
def permute(nums):
    result = []
    get_permute([], nums, result)
    return result

def get_permute(current, num, result):

    if not num:
        result.append(current+[])

    for i, v in enumerate(num):
        current.append(num[i])
        get_permute(current, num[:i] + num[i + 1:], result)
        current.pop()

if __name__ == "__main__":

    r = permute([1,2,3])

    for perm in r:
        print(perm)

如果我删除+[] ,则current + []result.append(current+[])做什么,它将打印空白列表。

它正在复制列表。 当您将其删除时,您会遇到问题,这是因为外部列表包含对同一列表的许多引用,而不是对许多不同列表的引用。

您应该能够用current.copy() (使用Python> = 3.3)或list(current)替换它,以避免将来的读者出现类似的困惑。 (有 。选择一个喜欢并坚持使用。)

+ []什么作用?

它会生成一个与旧列表具有相同内容的新列表。

>>> x = [1]
>>> id(x) == id(x + [])
False
>>> x == x + []
True

我为什么需要这个?

Whitout将副本添加到结果中时,结果中将有很多次相同的列表,并且每次更新该列表时,都会影响结果。

>>> x = [1, 2]
>>> result = []
>>> result.append(x)
>>> x.append(3)
>>> result.append(x)
>>> result
[[1, 2, 3], [1, 2, 3]]

一些使方法更具可读性的可能方法是

result.append(current[:])

要么

result.append(list(current))

如果删除+ []为什么它返回空白列表?

因为如果您不将副本附加到结果中,则结果中将只有一个列表,但是会出现多次。 而且您在此列表上调用.append(num[i])频率与.pop() ,导致该列表为空。

  相关解决方案