[英]When returning dictionaries, does python act like JavaScript?
I was wondering: 我在想:
def get_empty_cell():
return {'p': [[], []], 'h': {}, 'b': []}
def create_new_board(old_board):
height = len(old_board) + 4
width = len(old_board[0]) + 4
self.board = [None] * height
for i in range(0, height):
self.board[i] = [None] * width
for j in range(0, width):
# (!) deepcopy()
self.board[i][j] = copy.deepcopy(self.get_empty_cell())
I'm using deepcopy because I've had many situations where different variables access the same content. 我使用Deepcopy是因为我遇到过许多情况,其中不同的变量访问相同的内容。 But when Python returns "new" dictionaries like in my code, do I need to use
copy.deepcopy
if I want different cells or is it like JavaScript? 但是当Python像我的代码一样返回“新”字典时,如果我想要不同的单元格还是像JavaScript一样,我是否需要使用
copy.deepcopy
?
(and off topic: I'm sure my code could be optimized "the Python way"...) (以及主题之外:我确信我的代码可以通过“ Python方式”进行优化...)
get_empty_cell()
returns a new dictionary from a literal each time. get_empty_cell()
每次都从文字中返回一个新字典。 There's no need to copy it again. 无需再次复制。
As in the other answer, you don't need to make a copy because get_empty_cell()
returns a new dict
each time you call it. 与其他答案一样,您无需进行复制,因为每次调用
get_empty_cell()
返回一个新dict
。
And yes! 是的! you can optimize your code like this:
您可以像这样优化代码:
self.board = [[self.get_empty_cell() for j in range(width)] for i in range(height)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.