Python中的arr和arr [:]有什么区别?

时间:2019-11-05 01:07:48

标签: python python-3.x list

我想知道列表变量本身和后跟[:]

的列表变量之间的区别

例如

# When nums are List[int] and res are List,
# what is the difference between
res.append(nums[:])
# and 
res.append(nums)

我正在实现递归置换功能时出现了我的问题

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        self.helper(nums, 0, len(nums) - 1, res)
        return res

    def helper(self, nums, l, r, res):
        if l == r:
            res.append(nums[:]) # this will append unique combination
            res.append(nums) # this will result in a list full of same combinations
        else:
            for i in range(l, r + 1):
                nums[l], nums[i] = nums[i], nums[l]
                self.helper(nums, l + 1, r, res)
                nums[l], nums[i] = nums[i], nums[l]

谢谢您的帮助!

2 个答案:

答案 0 :(得分:4)

nums[:]是在python中创建列表的浅表副本的便捷方法。 res.append(nums)附加了对nums的引用,即对nums的任何更改也将反映在res中。 res.append(nums[:])将创建nums的新副本,您可以更改所有所需内容而无需更改nums的原始副本

希望这个例子清楚

nums = [1, 2, 3]
res = [nums]
res[0][0] = 'banana'
print(nums)

nums = [1, 2, 3]
res = [nums[:]]
res[0][0] = 'banana'
print(nums)

提供输出

  

['banana',2,3]
  [1、2、3]

答案 1 :(得分:0)

arr仅将指针复制到原始列表,而arr[:]创建arr的副本。

当我们对原始数组进行更改时,更改将反映在指针中,而不是副本中:

>>> foo = [1, 2, 3]
>>> pointer = foo
>>> acopy = foo[:]
>>> foo[0] = 'banana'
>>> foo
['banana', 2, 3]
>>> pointer
['banana', 2, 3]
>>> acopy
[1, 2, 3]

如果我们更改指针,则更改将反映在原始副本中,而不反映在副本中:

>>> pointer[0] = 'chocolate'
>>> foo
['chocolate', 2, 3]
>>> pointer
['chocolate', 2, 3]
>>> acopy
[1, 2, 3]

如果我们对副本进行更改,则更改与原始副本和指针无关:

>>> acopy[0] = 'monkey'
>>> acopy
['monkey', 2, 3]
>>> foo
['chocolate', 2, 3]
>>> pointer
['chocolate', 2, 3]