首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试对用户输入使用字典(python)

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

Stack Overflow用户
提问于 2020-02-08 11:19:13
回答 2查看 34关注 0票数 0

有人能帮我吗?我正在尝试找出如何简化这段代码。人们一直在建议使用字典,但我不知道是如何做到的。我只想缩短代码,并且不想使用太多的if语句。同样为了澄清,我想让用户输入一个英雄,并打印出一个不同的英雄。

代码语言:javascript
复制
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())
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-08 11:27:32

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

代码语言:javascript
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2020-02-08 11:38:51

你也可以这样做:

代码语言:javascript
复制
 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!")

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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60123637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档