简体   繁体   English

返回字典时,python的行为类似于JavaScript吗?

[英]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.

相关问题 javascript中是否有像python这样的字典? - are there dictionaries in javascript like python? Javascript - 使局部变量像全局一样 - Javascript - Make a local variable act like a global 像css3过渡一样的Javascript - Javascript that act like css3 transition 为什么JS日期会这样? - Why does the JS date act like this? javascript 中的 Python 字典 - Python dictionaries in javascript 从字符串转换为浮点数或整数时,为什么'+'表现为javascript中的解析,以及在性能方面有何不同? - Why '+' act like a parse in javascript when converting from string to float or integer and how it differs regarding on performance? jQuery .append()什么时候像.insertBefore()的最后一个孩子那样与记录的一样? - When does jQuery .append() act like .insertBefore() last child vs. as documented? 我使图像看起来像一个可单击的按钮,但是现在当我单击它时,它是否不充当超链接? - I made a image look like a clickable button, but now when I click on it, does not act as hyperlink? 为什么在使用jQuery的filter方法时* [checked]表现为:checked? - Why does *[checked] act like :checked when using jQuery's filter method? 在Python字典中解析JavaScript数组 - Parsing javaScript arrays in the Python dictionaries
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM