Py学习  »  Python

尝试对用户输入使用词典(python)

Cody Greathouse • 6 年前 • 1857 次点击  

有人能帮我吗?我正在想办法简化这段代码。人们一直建议用字典,但我不知道怎么用。我只想缩短代码的长度,而不是使用那么多if语句。同样为了澄清,我想让用户输入一个英雄,并有一个不同的英雄打印回来。

choice = str(input('Choose a hero\n'))

def hero_choose():
    if choice.lower() == 'batman':
        return('Moon Knight')
    if choice.lower() == 'moon knight':
        return('Batman')
    if choice.lower() == 'superman':
        return('Hyperion')
    if choice.lower() =='hyperion':
        return('Superman')
    if choice.lower() == 'thor':
        return('Shazam')
    if choice.lower() == 'shazam':
        return('Thor')
    if choice.lower() == 'red hood':
        return('punisher')
    if choice.lower() == 'punisher':
        return('Red Hood')
    if choice.lower() == 'wonder woman':
        return('Jean Grey')
    if choice.lower() == 'jean grey':
        return('Wonder Woman')
    if choice.lower() == 'iron man':
        return('Batwing')
    if choice.lower() == 'batwing':
        return('Iron Man')
    if choice.lower() == 'flash':
        return('Quicksilver')
    if choice.lower() == 'quicksilver':
        return('Flash')
    else:
        return('Your hero may not be available\nor your spelling may be wrong.')

print(hero_choose())
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54272
文章 [ 2 ]  |  最新文章 6 年前
FishingCode
Reply   •   1 楼
FishingCode    6 年前

你也可以这样做:

 hero_choices = { 'batman': 'Moon Knight',
                  'moon knight: 'Batman',
                  'superman':'Hyperion',
                  'hyperion': 'Superman',
                   ...
                }

 getChoice = str(input("Please choose a hero:\n"))


 for key, value in hero_choices.items():
    if key == "getChoice":
       print(hero_choices[key])
    elif key != "getChoice":
       print("This hero doesn't exist!")

这是上述方案的替代方案。

Nick
Reply   •   2 楼
Nick    6 年前

字典绝对是简化这段代码的最好方法。可以使用输入作为键设置所有选项,并使用默认参数 dict.get 要在出错时返回消息,请执行以下操作:

choice = str(input('Choose a hero\n'))

hero_choose = { 'batman' : 'Moon Knight', 
                'moon knight' : 'Batman',
                'superman' : 'Hyperion',
                'hyperion' : 'Superman'
                # ...
               }

hero = hero_choose.get(choice.lower(), 'Your hero may not be available\nor your spelling may be wrong.')

print(hero)