简体   繁体   English

附加列表与附加列表之间的区别[:]

[英]Difference between appending a list vs appending list[:]

I am trying to traverse into a string using DFS and appending it to result in the line highlighted.我正在尝试使用 DFS 遍历字符串并将其附加以突出显示该行。 However if I use result.append(currlist) vs result.append(currlist[:]) , the result is totally different.但是,如果我使用result.append(currlist)result.append(currlist[:]) ,结果是完全不同的。 The former doesn't work, why is that?前者不起作用,为什么?

class Solution: 
       
    def dfs(self, start, s, currlist, result):
        if start >= len(s):
            result.append(currlist[:])  # <--
            return
        
        for end in range(start, len(s)):
            currlist.append(s[start:end+1])
            self.dfs(end+1, s, currlist, result)
            currlist.pop()
        
    def partition(self, s: str) -> List[List[str]]:
        result = []
        self.dfs(0, s, [], result)
        return result

list[:] creates a copy of the object list[:]创建对象的副本

Example:例子:

x = []
y = [0, 1]

x.append(y)
print(x)

y[0] = 2

print(x)

Output:输出:

 [[0, 1]] [[2, 1]]
x = []
y = [0, 1]

x.append(y[:])
print(x)

y[0] = 2

print(x)

Output:输出:

 [[0, 1]] [[0, 1]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM