有人能帮我吗?我正在尝试找出如何简化这段代码。人们一直在建议使用字典,但我不知道是如何做到的。我只想缩短代码,并且不想使用太多的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())发布于 2020-02-08 11:27:32
字典绝对是简化这段代码的最佳方式。您可以使用输入作为键来设置所有选项,并使用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)发布于 2020-02-08 11:38:51
你也可以这样做:
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!")这是上述解决方案的替代方案。
https://stackoverflow.com/questions/60123637
复制相似问题