相同列表功能的输出不同

为什么输出不同?

n = 5

##################################

dp  = [[False]*n]*n

# make diagonal True 
for i in range(n): dp[i][i] = True

print("CASE #1")
for i in dp: print(i)

##################################

dp = [[False for i in range(n)] for j in range(n)]

# make diagonal True 
for i in range(n): dp[i][i] = True

print("CASE #2")
for i in dp: print(i)
CASE #1
[True, True, True, True, True]
[True, True, True, True, True]
[True, True, True, True, True]
[True, True, True, True, True]
[True, True, True, True, True]
CASE #2
[True, False, False, False, False]
[False, True, False, False, False]
[False, False, True, False, False]
[False, False, False, True, False]
[False, False, False, False, True]

I am not able to justify the output for case 1. Is it one pointer/reference (n size array of False) that is copied n times? Can someone explain how is dp created in the first case?

评论
涂鸦
涂鸦

是的,如果它们全部都具有相同的指针(我们在python中称身份)。 尝试:

id(dp[0]) == id(dp[1])

两种情况都需要澄清

refer this for more clarification List of lists changes reflected across sublists unexpectedly

点赞
评论
喂圆圆
喂圆圆

在第一种情况下,您在链接到它的列表列表中有一个项目。因此,当您更改此值时,链接将引用新值。

点赞
评论