繁体   English   中英

识别一个字典中的键,并使用它来修改另一个字典的值

[英]Identifying a key in one dict, and using it to modify values of another dict

对于我正在创建的基于文本的RPG,我有一些字典,概述了各种游戏中的宗教,种族等。这些宗教的某些价值包括玩家数据的增益,例如:

religion_Dict = {'Way of the White': {'buffs': {'intelligence': 5, 'defense': 3},
                                     'abilities': [...],
                                     'description': '...'}}

我的问题是在尝试将宗教的属性加法器应用到玩家的属性时出现的。 如果我有一个类似于以下内容的播放器类:

class Player(object)    
    def __init__(self):
        ...
        self.religion = None
        self.stats = {'intelligence': 10, 'defense': 8}

现在,让我们假设玩家加入宗教Way of the White ,我怎么去识别键intelligencedefense和它们各自的值-字典里面religion_dict -并把它们应用到玩家的价值观stats字典?

我知道我可以使用religion_Dict.keys()或基本的for循环来提取键名,但是如何使用它来正确地修改相应的玩家状态值呢?

我确定我只是缺少一个基本概念。 无论如何,感谢任何愿意帮助回答这个简单问题的人! 我很感激!

这是您将如何做的草图:

religion_Dict = {'Way of the White': {'buffs': {'intelligence': 5, 'defense': 3},
                                     'abilities': [...],
                                     'description': '...'}}
buffs = religion_Dict['Way of the White']['buffs']

for key in buffs:
    player.stats[key] = player.stats.get(key,0) + buffs[key]

当然,您应该将此逻辑包装在Player类的方法中,但是上面的逻辑正是您要寻找的。 请注意, .get方法采用第二个参数,这是默认值,如果没有键值,则返回该默认值。 因此,此行会将1加到任何状态,如果不存在,则将1加0。

这会向Player添加一个方法,该方法将字典中的值分配给玩家统计信息。 它使用get来确保该值在字典中并且包含字段buffs 如果是这样,它将获取intelligencedefense的值,并将其添加到玩家的统计数据中。

class Player(object)    
    def __init__(self):
        ...
        self.religion = None
        self.stats = {'intelligence': 10, 'defense': 8}

    def join_religion(religion):
        stats = religion_dict.get(religion)
        if stats and 'buffs' in stats:
            self.intelligence += stats['buffs'].get('intelligence', 0)
            self.defense += stats['buffs'].get('defense', 0)

p = Player()
p.join_religion('Way of the White')
self.stats = religion_Dict['Way of the White']['buffs']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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