这与leetcode问题#39有关。我从results.append(solution)开始,它没有正确地附加到列表中,并且在results.append(solution[:])工作的解决方案中找到了它。这两种语法有什么区别?
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
results=[]
def backtracking(candidates,target,start,solution,results):
#print(start,target,solution,results)
if target<0:
return
if target==0:
results.append(solution[:])
return
for i in range(start,len(candidates)):
solution.append(candidates[i])
backtracking(candidates,target-candidates[i],i,solution,results)
solution.pop()
backtracking(candidates,target,0,[],results)
return results发布于 2020-04-30 15:51:26
a[:]将创建一个新列表。c.append(b)将列表b附加到c。
下面的代码将有助于更好地理解这一点-
>>> a=[1,2,3]
>>> b=[4,5]
>>> c=[1,2,3]
>>> a.append(b) #append b
>>> c.append(b[:]) #create new list and append
>>> a
[1, 2, 3, [4, 5]]
>>> c
[1, 2, 3, [4, 5]]
>>> b
[4, 5]
>>> a[3][0]=99 #modify a
>>> a
[1, 2, 3, [99, 5]] #a modified
>>> b
[99, 5] #so does b
>>> c
[1, 2, 3, [4, 5]] #modify c
>>> c[3][1]=99
>>> c #c modified
[1, 2, 3, [4, 99]]
>>> b #original b did not get modified
[99, 5]
>>>发布于 2020-04-30 15:51:02
从对象的id中可以看到,切片创建了一个新列表
>>> a = [1, 2, 3]
>>> id(a)
2711680383816
>>> id(a[:])
2711683338696而将列表直接分配给同一个对象
>>> b = a
>>> id(b)
2711680383816发布于 2020-04-30 16:07:15
a是一个列表,a[:]是一个新列表,所有元素都被复制。
>>> a = [1, 2, 3]
>>> a == a[:]
True
>>> a is a[:]
False让我们有另一个列表b = ["a", "b"]。append将你给它的任何东西添加到列表的末尾。如果追加另一个列表,则会添加对该列表的引用,并可能导致未预期的行为:
>>> b.append(a)
>>> b
["a", "b", [1, 2, 3]]
>>> a[0] = "c"
>>> b
["a", "b", ["c", 2, 3]]
>>> b[2][1] = 42
>>> a
["c", 42, 3]
>>> a is b[2]
True您可以看到,在追加a之后,如果您更改了a中的一个元素,它也会在b中发生变化。这是因为b只有一个对a的引用。为了防止出现这种情况,您可以使用b.append(a[:])。这将复制a中的值,因此当您更改a中的值时,b中的值将保持复制时的状态:
>>> b.append(a)
>>> b
["a", "b", [1, 2, 3]]
>>> a[0] = "c"
>>> b
["a", "b", [1, 2, 3]]
>>> b[2][1] = 42
>>> a
["c", 2, 3]
>>> a is b[2]
False因此,在您的问题中,使用solution[:]确保在results循环的下一个迭代中发生solution.append时,向for添加的内容不会改变。
https://stackoverflow.com/questions/61527391
复制相似问题