Py学习  »  Python

Python生成排列时添加到列表的方式不正确

atkayla • 5 年前 • 1474 次点击  

在本例中,为什么会生成正确的结果:

nxt = path + [nums[i]]

但不是:

nxt = path ; nxt += [nums[i]]
nxt = path ; nxt.append(nums[i])
def permute(nums):
    def dfs(nums, path):
      if not nums: # empty, done with path
          all_perms.append(path)
          return

      for i in range(len(nums)):
        nxt = path + [nums[i]]
        # nxt = path ; nxt += [nums[i]]
        # nxt = path ; nxt.append(nums[i])
        print(nxt)
        dfs(nums[:i] + nums[i+1:], nxt)

    all_perms = []
    dfs(nums, [])
    return all_perms
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54764
 
1474 次点击  
文章 [ 1 ]  |  最新文章 5 年前
mkrieger1
Reply   •   1 楼
mkrieger1    5 年前

在本例中,为什么会生成正确的结果:

nxt = path + [nums[i]]

这就离开了 path

但不是:

nxt = path ; nxt += [nums[i]]
nxt = path ; nxt.append(nums[i])

本附录 nums[i] 路径 这显然是不正确的。