A tic-tac-toe where X wins in the first attempt!/一蹴即至!

問題來源:

https://github.com/leisurelicht/wtfpython-cn

問題:

代碼_2中的各個元素的地址仍和代碼_1中的一致,爲啥對board[0][0]進行修改,沒有影響到相同存儲單元的同一個對象—>發生字符串駐留現象

問題解決:

代碼_2 中遍歷board的每個i都是不一樣的
代碼_1 中遍歷board的每個i都是一樣的
代碼_2 圖例:
在這裏插入圖片描述
代碼_1 圖例:
在這裏插入圖片描述

代碼_1:

row=['']*3
for i in row:
    print(id(i))   
board=[row]*3
for i in board:
    print(id(i[0]),id(i[2]),id(i[1]))
board[0][0]='y'
board

輸出結果_1:

140302724827824
140302724827824
140302724827824
140302724827824 140302724827824 140302724827824
140302724827824 140302724827824 140302724827824
140302724827824 140302724827824 140302724827824
[['y', '', ''], ['y', '', ''], ['y', '', '']]

代碼_2:

board_after=[['']*3 for _ in range(3)]
for i in board_after:
    print(id(i[0]),id(i[2]),id(i[1]))
board_after[0][0]='x'
board_after

輸出結果_2:

140302724827824 140302724827824 140302724827824
140302724827824 140302724827824 140302724827824
140302724827824 140302724827824 140302724827824
[['x', '', ''], ['', '', ''], ['', '', '']]

有趣兒

代碼_3

ouput=[1]*3
ouput[2]=10
print(ouput)
for i in ouput:
    print(id(i))

輸出結果_3

[1, 1, 10]
140732420707360
140732420707360
140732420707648
剛開始指向同一個對象,後來被賦值成10,又指向另一個對象
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章