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,又指向另一个对象
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章