python 中有取代if-elif-else
的东西吗
要是这样的呢:
if y == 'a': if x < =10: a = function(1) elif x > 10 and x <= 30: a =function(2) else: a = function(3) elif y =='b': if x < =11: a = function(2) elif x > 11 and x <= 30: a =function(3) else: a = function(4) elif y == 'c': if x < =30: a = function(3) else: a = function(4) else: return false
所以说, 我还是觉得用if-elif-else
没什么不好的
f = lambda x: 1 if x<=10 else 2 if x<=30 else 3 dic = {1:function(1),2:function(2),3:function(3)} a = dic[f(x)]
我覺得如果那麼短,使用 if/elif/else
也未嘗不可,倒是有一點可以補充,Python 允許一般數學上的不等式寫法,不必拆開來再用 and
連接:
if x < =10:
a = function(1)
elif 10 < x <= 30:
a = function(2)
else:
a = function(3)
其實我覺得過猶不及,有的時候為了想寫漂亮卻越來越複雜了,我覺得簡單是最重要的,簡單不是簡陋
簡單即優雅
我回答過的問題: Python-QA
实在嫌麻烦,可以自己实现一个switch case
嘛
d = {'a':function(1),'b':function(2),'c':function(3)}
a = x <= 10 and 'a' or (10 < x <=30 and 'b' or 'c')
d[a]
手机写代码简直痛不欲生。。
可以使用字典来实现来实现这个功能
存在即合理。正常情况下,集中条件判断都很好换着写同样的功能。不过,if-elif-else的阅读性真的很好。至于效率的话,等你涉及到时间复杂度及算法优化等性能问题时,你就会发现很多优秀的算法中,也会用if-elif-else。