简体   繁体   中英

Incrementing list values

I have a player template that I am copying, setting a field, and then appending the updated template to a new list.

player_template = {
    "player": "",
    "hand": [
        {0 :
            {
                "cards_in_hand": [],
                "cards_taken": []
            }
        }
    ]
}

However, when I go to do a range loop to create multiple players, it only creates the last player multiple times.

for i in range(4):
        p["player"] = i
        players.append(p)

Output:

[
    {
        'player': 3,
        'hand': [
            {
                0: {
                    'cards_in_hand': [],
                    'cards_taken': []
                }
            }
        ]
    },
    {
        'player': 3,
        'hand': [
            {
                0: {
                    'cards_in_hand': [],
                    'cards_taken': []
                }
            }
        ]
    },
    {
        'player': 3,
        'hand': [
            {
                0: {
                    'cards_in_hand': [],
                    'cards_taken': []
                }
            }
        ]
    },
    {
        'player': 3,
        'hand': [
            {
                0: {
                    'cards_in_hand': [],
                    'cards_taken': []
                }
            }
        ]
    }
]

I've tried range(start, stop, step) , but it also produces the same results. How can I get the output to be player 1, player 2, etc.?

Currently you're overriding the previous player with each iteration. This is because dictionaries are mutable objects and you're poinging to the same one.

You need to deep-copy the mapping that represents a player:

import copy

for i in range(4):
    p["player"] = i
    players.append(copy.deepcopy(p))

I've used copy.deepcopy but you can do this manually if you want.

A better way would be to use an actual class to reperesent a Player .

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