Python:嵌套字典问题:尝试运行“if”命令打印字符串

2024-09-30 20:32:34 发布

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

我正在尝试为此嵌套字典执行以下两项操作:

  1. 如果一只鸟具有攻击性,请打印一条字符串,建议我们使用此打印语句中的“动作”列表“遮住头部”

  2. 如果一只鸟濒临灭绝,请打印一个字符串,建议我们“后退”,并使用此打印语句中的操作列表

这是我到目前为止所拥有的。非常感谢您的帮助!:

rarebirds = {
    'Gold-crested Toucan': {
        'Height (m)': 1.1,
        'Weight (kg)': 35,
        'Color': 'Gold',
        'Endangered': True,
        'Aggressive': True},

'Pearlescent Kingfisher': {
        'Height (m)': 0.25,
        'Weight (kg)': 0.5,
        'Color': 'White',
        'Endangered': False,
        'Aggressive': False},

'Four-metre Hummingbird': {
        'Height (m)': 0.6,
        'Weight (kg)': 0.5,
        'Color': 'Blue',
        'Endangered': True,
        'Aggressive': False},

'Giant Eagle': {
        'Height (m)': 1.5,
        'Weight (kg)': 52,
        'Color': 'Black and White',
        'Endangered': True,
        'Aggressive': True},

'Ancient Vulture': {
        'Height (m)': 2.1,
        'Weight (kg)': 70,
        'Color': 'Brown',
        'Endangered': False,
        'Aggressive': False}
}

actions = ['Back Away', 'Cover our Heads', 'Take a Photograph']


for key, value in rarebirds.items():
    for value in value:
        if value == 'Aggressive' and True:
            print(key, ":", actions[1])
            return

for key, value in rarebirds.items():
     for value in value:
         if value == 'Endangered' and True:
         print(key, ":", actions[0])
         return

Tags: andkeyinactionsfalsetrueforvalue
3条回答
final_actions={}
for key, value in rarebirds.items():
    if final_actions.get(key)==None:
        final_actions[key]=[]
    if 'Aggressive' in value and value.get("Aggressive")==True:
        final_actions[key].append(actions[1])
    if 'Endangered' in value and value.get("Endangered")==True:
        final_actions[key].append(actions[0])
    if ('Aggressive' in value and value.get("Aggressive")==False) and ('Endangered' in value and value.get("Endangered")==False):
        final_actions[key].append(actions[2])
print(final_actions)

您将得到以下答案:

{
   "Four-metre Hummingbird":[
      "Back Away"
   ],
   "Giant Eagle":[
      "Cover our Heads",
      "Back Away"
   ],
   "Gold-crested Toucan":[
      "Cover our Heads",
      "Back Away"
   ],
   "Pearlescent Kingfisher":[
      "Take a Photograph"
   ],
   "Ancient Vulture":[
      "Take a Photograph"
   ]
}

而且

   for value in value:
        if value == 'Aggressive' and True:

上面的代码在您的代码中是错误的。 你可以试试看,而不是这个

for nested_value in value:
        if nested_value == 'Aggressive' and value.get(nested_value)==True:

另一种方法是将名称和操作序列构建为元组

这里的目的是展示生成器的使用,这有助于避免构建额外的数据结构(请注意,甚至每个元组都可以被生成器替换,具体取决于它的使用)

例如,假设您只能拍摄中性物种的照片:

rarebirds = {
    'Gold-crested Toucan': {
        'Height (m)': 1.1,
        'Weight (kg)': 35,
        'Color': 'Gold',
        'Endangered': True,
        'Aggressive': True},

'Pearlescent Kingfisher': {
        'Height (m)': 0.25,
        'Weight (kg)': 0.5,
        'Color': 'White',
        'Endangered': False,
        'Aggressive': False},

'Four-metre Hummingbird': {
        'Height (m)': 0.6,
        'Weight (kg)': 0.5,
        'Color': 'Blue',
        'Endangered': True,
        'Aggressive': False},

'Giant Eagle': {
        'Height (m)': 1.5,
        'Weight (kg)': 52,
        'Color': 'Black and White',
        'Endangered': True,
        'Aggressive': True},

'Ancient Vulture': {
        'Height (m)': 2.1,
        'Weight (kg)': 70,
        'Color': 'Brown',
        'Endangered': False,
        'Aggressive': False}
}

actions = ['Back Away', 'Cover our Heads', 'Take a Photograph']

def show_actions(birds):
    for name, attrs in birds.items():
        acs = []
        if attrs['Aggressive']:
            acs.append(actions[1])
        if attrs['Endangered']:
            acs.append(actions[0])
        if not acs:
            acs.append(actions[2])
        yield (name, *acs)

for bird, *acs in show_actions(rarebirds):
    print(f"{bird}: {', '.join(acs)}")

产生

Gold-crested Toucan: Cover our Heads, Back Away
Pearlescent Kingfisher: Take a Photograph
Four-metre Hummingbird: Back Away
Giant Eagle: Cover our Heads, Back Away
Ancient Vulture: Take a Photograph

确定的问题:

  1. 第二个for循环中的缩进问题
  2. return语句不是必需的
  3. if value == 'Aggressive' and True:-对于将Aggressive作为其值之一的所有键,无论它是True还是False,此条件都为真

因为rarebirds是一个dict,所以我们不想遍历value。它可以简单地写为

for key, value in rarebirds.items():
    if value['Aggressive'] == True:
        print(key + ":" + actions[1])

for key, value in rarebirds.items():
    if value['Endangered'] == True:
        print(key + ":" + actions[0])

对于输出

Gold-crested Toucan:Cover our Heads
Giant Eagle:Cover our Heads
Gold-crested Toucan:Back Away
Four-metre Hummingbird:Back Away
Giant Eagle:Back Away

相关问题 更多 >