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

问题描述 投票:1回答:2

我想知道列表变量本身与列表变量之间的区别,后跟[:]

例如,

# 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]

感谢您的事先帮助!

python python-3.x list
2个回答
2
投票

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)

给出输出

['香蕉',2,3][1、2、3]

[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]

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.