简体   繁体   中英

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. 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?

(and off topic: I'm sure my code could be optimized "the Python way"...)

get_empty_cell() returns a new dictionary from a literal each time. 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.

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM