Python遍历字典,确定给定的字符串是否匹配任何名称值

2024-09-27 09:25:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我查看了this post试图找出如何找出给定字符串是否与字典中的某个值匹配,但它没有返回任何内容。我有一个包含字典的字典,我正在尝试找出我如何,假设给定一个字符串'warrior',检查字典,进入子字典,检查给定字符串的name键,如果它存在,返回类。这是我的密码。你知道吗

你知道吗类.py你知道吗

#import playerstats
from player import playerStats

def setClass(chosenClass):
    chosenClass = chosenClass.upper()
    #function from post
    """print ([key
              for key, value in classes.items()
              if value == chosenClass])"""
    #this returns nothing
    for key, value in classes.items():
        if value == chosenClass:
            print(classes[chosenClass][value])
    #also returns nothing
    for i in classes:
        if classes[i]["name"] == chosenClass:
            print('true')

#create classes
classes = {
    'WARRIOR': {
        #define name of class for reference
        'name': 'Warrior',
        #define description of class for reference
        'description': 'You were  born a protector. You grew up to bear a one-handed weapon and shield, born to prevent harm to others. A warrior is great with health, armor, and defense.',
        #define what the class can equip
        'gearWeight': ['Cloth', 'Leather', 'Mail', 'Plate'],
        #define stat modifiers
        'stats': {
            #increase, decrease, or leave alone stats from default
            'maxHealth': playerStats['maxHealth'],
            'stamina': playerStats['stamina'] * 1.25,
            'resil': playerStats['resil'] * 1.25,
            'armor': playerStats['armor'] * 1.35,
            'strength': playerStats['strength'] * 0.60,
            'agility': playerStats['agility'],
            'criticalChance': playerStats['criticalChance'],
            'spellPower': playerStats['spellPower'] * 0.40,
        }
    }
}

你知道吗播放器.py你知道吗

import random
import classes

#set starter gold variable
startGold = random.randint(25,215)*2.5
#begin player data for new slate
playerStats = {
    'currentHealth': int(100),
    'maxHealth': int(100),
    'stamina': int(10),
    'resil': int(2),
    'armor': int(20),
    'strength': int(15),
    'agility': int(10),
    'criticalChance': int(25),
    'spellPower': int(15),
    #set gold as random gold determined from before
    'gold': startGold,
    'name': {'first': 'New', 'last': 'Player'},
}

如果chosenClass是一个现有的类字典,我该怎么做才能让它在字典中搜索呢?你知道吗


Tags: 字符串namefromimportfor字典valueclasses
1条回答
网友
1楼 · 发布于 2024-09-27 09:25:16
....
    #this returns nothing
    for key, value in classes.items():
        if value == chosenClass:

我认为应该比较keychosenClass,而不是循环中的value。一个简单的故障排除工具是打印资料以查看发生了什么

....
    #this returns nothing
    for key, value in classes.items():
        print('key:{}, value:{}, chosenClass:{}'.format(key, value, chosenClass)
        if value == chosenClass:

但也许更简单的方法是:

def setClass(chosenClass):
    chosenClass = chosenClass.upper()
    chosen = classes.get(chosenClass, False)
    return chosen

相关问题 更多 >

    热门问题