【问题标题】:python 3.4 - input, match key, print valuepython 3.4 - 输入,匹配键,打印值
【发布时间】:2015-05-18 01:11:44
【问题描述】:

这是我第一次在这里提问,所以如果我遗漏了什么,请原谅我。

我是一名初级程序员,我从 python 3.4 开始。

我已经创建了一个函数(如下),它在执行时工作正常,但我正在尝试压缩我的代码占用空间。

def PwrPriSel (PwrPri):
#Physical Abilities
Dismiss1 = "I'm sorry, but you are not the person I have been waiting for."
Dismiss2 = "Please answer the question"
PhyPwr = 'Strength, Flight, Speed, Invisibility, Invincibility, Shapeshift: '
Strength = "Your Strenth will be overwhelming, your resolve un-wavering. You will be a hammer made of flesh."
Flight = "You will be at home in the sky. You will feel as light as air, able to leap to enormous heights and control your descent with sheer willpower. With mastery wings will form and you will become a creature of the heavens."
Speed = "Time will be your slave. With mastery of this ability, life is controllable."
Invisibility = "Move unseen, unheard and unknown. In time, true mastery will be evident when reality forgets you are there."
Invincibility = "You will not be harmed or negatively affected by any event unless you wish to be harmed and to a specific extent."
Shapeshift = "You can change the way you look and how you sound by willing it to be. With mastery your form can transform into a desired being instead of just impersonation."
PhyPwrDict = {"Strength" : Strength, "Flight" : Flight, "Speed" : Speed, "Invisibility" : Invisibility, "Invincibility" : Invincibility, "Shapeshift" : Shapeshift}


if PwrPri == 'Strength':
  print(PwrPri)
  print(PhyPwrList[0])
elif PwrPri == 'Flight':
  print(PwrPri)
  print(PhyPwrList[1])
elif PwrPri == 'Speed':
  print(PwrPri)
  print(PhyPwrList[2])
elif PwrPri == 'Invisibility':
  print(PwrPri)
  print(PhyPwrList[3])
elif PwrPri == 'Invincibility':
  print(PwrPri)
  print(PhyPwrList[4])
elif PwrPri == 'Shapeshift':
  print(PwrPri)
  print(PhyPwrList[5])
else:
  print(Dismiss2)
  sys.exit(0)

PhyPwrDict 以前是我从中调用索引的列表,但我希望我的代码更加动态。

我现在已经研究了大约 2 天,但我发现的示例都没有达到我想要的效果。

我希望将 PwrPri 的任何输入与我的 PhyPwrDict 字典中的所有键进行比较,当找到键匹配时,我希望将值(包含描述键的信息的变量)打印在屏幕上,所以如果说;

PwrPri = Strength 的输入,PhyPwrDict 应该搜索Strength 键,找到后打印Strength 变量的内容。

【问题讨论】:

    标签: python footprint


    【解决方案1】:

    你所有的if .. elif .. else 逻辑都可以用这个替换:

    if PwrPri in PhyPwrDict:
        print(PhyPwrDict[PwrPri])
    else:
        print(Dismiss2)
        sys.exit(0)
    

    这表示,“如果PwrPri 键在字典中,则打印其对应的值,否则打印Dismiss2 并退出”。

    【讨论】:

    • 这正是我想要的,谢谢你!!。
    猜你喜欢
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多