简体   繁体   English

如何使用 dict 优化我的代码?

[英]How can I do to optimize my code using dict?

I have this code:我有这个代码:

a = ""
b = ""
if a == "Hello":
    b = "Hi"
elif a == "Bye":
    b = "Good Bye"

I thought to use something like that:我想使用类似的东西:

mydict = {"Hello": "Hi", "Bye": "Good Bye"}

and use a lambda function which consist in looking at the keys of mydict and apply the value in function of the value of the variable a.并使用 lambda function 包括查看 mydict 的键并应用变量 a 的值的 function 中的值。

Di you have others ideas?你有其他想法吗?

Thank you very much !非常感谢 !

Yes.是的。 You've got the idea.你有这个想法。 Try this.尝试这个。

mydict = {"Hello": "Hi", "Bye": "Good Bye"}
print(mydict.get(input('Greet: ')))

No need for lambda.不需要 lambda。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM