其他語言中,switch語句大概是這樣的
switch (var)而python本身沒有switch語句,解決方法有以下3種:
a.使用dictionary
values =
values.get(var, do_default_stuff)()
b.使用lambda
result = [value](x)
c.brian beck提供了乙個類 switch 來實現其他語言中switch的功能
# 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"""
ifself.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
# 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'):
1break
if case('two'):
2break
if case('ten'):
10break
if case('eleven'):
11break
if case(): # default, could also just omit condition or 'if true'
"something else!"
# no need to break here, it'll stop anyway
python中 python中的 與
這一部分首先要理解python記憶體機制,python中萬物皆物件。對於不可變物件,改變了原來的值,其別名 變數名 繫結到了新值上面,id肯定會改變 對於可變物件,操作改變了值,id肯定會變,而 是本地操作,其值原地修改 對於 號操作,可變物件和不可變物件呼叫的都是 add 操作 對於 號操作,可變...
python中否定for 在python中否定函式
有沒有一種方法可以否定乙個函式,使它返回負數。在我的函式中,我有條件句,每個條件句都讓這個 烏龜 移動。有沒有一種方法可以否定這一點,所以烏龜的每乙個動作都是否定的。我說的是 狀況 在def ttinterpret program interpret program as a tinyturtle ...
python中雙重迴圈 加速Python中的雙迴圈
有沒有辦法加快從上一次迭代更新其值的雙迴圈?在 中 def calc n,m x 1.0 y 2.0 container np.zeros n,2 for i in range n for j in range m x np.random.gamma 3,1.0 y y 4 y np.random....