我希望能够循环遍历游戏中的所有对象并检查它们的 self.owner 统计数据。
为此,我这样做:
for ship in game_map._all_ships():
....
我想制作一个字典,其中键为玩家,船的值列表为:
dictionary { 'Player 0' :[ship 1, ship 2], 'Player 1': [ship 1] ... etc}
我可以使用
检索他们的播放器ship.owner
但我不知道如何用列表初始化字典,而不知道有多少玩家或他们有多少艘船,而不先运行循环。
最佳答案
最平滑的方法使用 collections.defaultdict
为了避免检查 key :
from collections import defaultdict
dic = defaultdict(list)
for ship in game_map._all_ships():
dic[ship.owner].append(ship)
关于python - 创建一个具有未知键的字典并向其附加一个列表值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47979374/