A pitfall in list creation - changing one value will also change the rest of the values

dp = [[float('inf')]*2]*(2+1)
dp1 = [[float('inf')]*2 for _ in range(2+1)]
dp[1][0] = 1
dp1[1][0] = 1
print((dp))
print((dp1))

[[1, inf], [1, inf], [1, inf]]
[[inf, inf], [1, inf], [inf, inf]]

Because multiplication refers to the referenced address, the for loop creates a new address memory
You can also use deep copy to solve it

Guess you like

Origin blog.csdn.net/wuxulong123/article/details/124075413