Python把同一个对象循环赋值给另外一个变量
Python把同一个对象循环赋值给另外一个变量,修改一个对象,其他对象也修改了
>>> row=['_'] * 3 >>> board = [] >>> for i in range(3): ... board.append(row) ... >>> row ['_', '_', '_'] >>> board [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] >>> board[2][1]='A' >>> row ['_', 'A', '_'] >>> board [['_', 'A', '_'], ['_', 'A', '_'], ['_', 'A', '_']] #3个子对象都被修改了 >>>
如果不想复制对象,可以在循环赋值前初始化下被赋值的变量
>>> board = [] >>> for i in range(3): ... row=['_'] * 3 #循环赋值前,初始化下变量 ... board.append(row) ... >>> board [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] >>> row ['_', '_', '_'] >>> board[2][0] = 'X' >>> board [['_', '_', '_'], ['_', '_', '_'], ['X', '_', '_']] >>> row ['X', '_', '_'] >>>