標籤:

Python中為什麼沒有switch語法結構,有什麼代替方案嗎?

網上很多都是用字典來映射的,但個人感覺有違Python簡潔、「懶惰」的原則,但用elif又怕影響效率,哪位牛牛來拋個糞糞來解決下內急啊?


Python的官方文檔上的解釋:

Design and History FAQ


網上很多都是用字典來映射的,但個人感覺有違Python簡潔、「懶惰」的原則

在C艹裡面,他們管這個叫表驅動。

事實證明論簡潔明了好維護,這個東西吊打switch。

不然別人也不會蛋疼搞出這個幺蛾子。

不然就算搞出來了也沒人會用。

說switch簡潔的都是沒見過幾百個case的switch的。

----------------------------

寫法我就不解釋,很多答主都解釋過了。

我就吐槽下。


def case1(somearg):
pass
def case2(somearg):
pass
def case3(somearg):
pass

switch={
1: case1,
2: case2,
3: case3
}

switch[case](arg)


http://code.activestate.com/recipes/410692/

# http://code.activestate.com/recipes/410692/
# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.

class switch(object):
def __init__(self, value):
self.value = value
self.fall = False

def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration

def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False

if __name__ == "__main__":

# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = ten
for case in switch(v):
if case(one):
print 1
break
if case(two):
print 2
break
if case(ten):
print 10
break
if case(eleven):
print 11
break
if case(): # default, could also just omit condition or if True
print "something else!"
# No need to break here, itll stop anyway

# break is used here to look as much like the real thing as possible, but
# elif is generally just as good and more concise.

# Empty suites are considered syntax errors, so intentional fall-throughs
# should contain pass
c = z
for case in switch(c):
if case(a): pass # only necessary if the rest of the suite is empty
if case(b): pass
# ...
if case(y): pass
if case(z):
print "c is lowercase!"
break
if case(A): pass
# ...
if case(Z):
print "c is uppercase!"
break
if case(): # default
print "I dunno what c was!"

# As suggested by Pierre Quentel, you can even expand upon the
# functionality of the classic case statement by matching multiple
# cases in a single shot. This greatly benefits operations such as the
# uppercase/lowercase example above:
import string
c = A
for case in switch(c):
if case(*string.lowercase): # note the * for unpacking as arguments
print "c is lowercase!"
break
if case(*string.uppercase):
print "c is uppercase!"
break
if case(!, ?, .): # normal argument passing style also applies
print "c is a sentence terminator!"
break
if case(): # default
print "I dunno what c was!"

# Since Pierres suggestion is backward-compatible with the original recipe,
# I have made the necessary modification to allow for the above usage.


def s(x):
return{
a:10,
b:20,
}.get(x,99)


if xxx:
xxx
elif xxx:
xxx
elif xxx:
xxx
else:
xxx

挺好用的...


實現Switch Case需要被判斷的變數是可哈希的和可比較的,這與Python倡導的靈活性有衝突。在實現上,優化不好做,可能到最後最差的情況彙編出來跟If Else組是一樣的。所以Python沒有支持。

---------------------

以上來自Python官方說法:PEP 3103 - A Switch/Case Statement.


搬運工,Switch statements in Python

使用拉姆達表達式

And here』s the equivalent code in Python:

result = {
a: lambda x: x * 5,
b: lambda x: x + 7,
c: lambda x: x - 2
}[value](x)


如果處理邏輯參數形式一致,使用字典等很方便,如果不一致呢?

程序的各種結構不是用來做萬能處理的,而是基於具體情況選擇的。否則有while,何必用for?


用字典,可以實現,執行效率高於 if....elif....elif......else

舉個簡單的加減乘除例子吧:

operation={+:x+y,-:x-y,*:x*y,/:x/y}

print opration.get(+,erroy)


用數組,列表或字典都很方便


推薦閱讀:

高德API+Python解決租房問題
Python 有哪些好的學習資料或者博客?
Python 3新特性匯總(一)
scala和groovy的優勢有哪些?
Python並發學習筆記:從協程到GEVENT(一)

TAG:Python |