python的switch
A. python中有switch嗎
python中沒有switch結構,一般用字典(dict)來模擬switch實現
B. python 怎麼根據參數執行不同的函數
使用字典,比如下面這樣:
1
2
3
4
5
6
7
8
9
10
11
12
13
def funcA():
pass
def funcB():
pass
def func_None():
print "cannot find func"
func_dict = {"a": funcA, "b": funcB}
def func(x):
return func_dict.get(x, func_None)()
在有switch的語言中,一般都是使用switch來根據入參進行判斷。但是python中沒有switch,因為根本不需要!!使用字典代替switch,性能更高,而且這種方法的表述能力更強一點。
另外func_dict.get(x, func_None)()中方法是從字典中取出值對應的函數對象,然後後面加上()是執行該對象的__call__方法。因為python中函數就是實現了__call__方法的對象。所以可以這么使用。
C. 為什麼Python中沒有Switch/Case語句
因為作為一門解釋型語言,switch/case是沒有存在必要的,if/elif/else就可以實現的功能,為什麼要再提供重復的?
if else的得一個if一個if的判斷過去,如果匹配的是最後一個條件,前面所有if都得判斷一遍的。
看過匯編就知道,C語言的switch/case,在case值連續的時候,是可以根據case值直接計算該跳轉的地址的。
D. python中有switch語句嗎
python官網的回答(地址:https://docs.python.org/2/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python):
You can do this easily enough with a sequence of if... elif... elif... else.
意思就是:python語法講究簡單明了,if else完全可以很簡單的實現switch的所有功能,沒必要用switch。
E. python查看數據集的結構 (用dict實現switch-case)
做機器學習的經常需要處理數據集,可能是json,mat,h5各種格式的,裡面有各種標簽結構。
了解數據集的結構、格式、類型燃陵,對我行橋們處理數據是有幫助的。
寫了一個有通用性的程序,
在此用來查看mscoco數據集的json注釋,相同級別的數據使用了相同的縮進。
這里列舉了對5種類型的處皮帶戚理,要處理其他類型,仿照加進去就是了。
python沒有switch-case結構,可以用dict實現。
運行結果:
可以清晰的看出,annotations是dict類型,有5個key,以及每個項分別的類型和詳情。
F. Python里怎麼實現switch case
學習Python過程中,發現沒有switch-case,過去寫C習慣用Switch/Case語句,官方文檔說通過if-elif實現。所以不妨自己來實現Switch/Case功能。
方法一
通過字典實現
def foo(var):
return {
'a': 1,
'b': 2,
'c': 3,
}.get(var,'error') #'error'為默認返回值,可自設置
方法二
通過匿名函數實現
def foo(var,x):
return {
'a': lambda x: x+1,
'b': lambda x: x+2,
'c': lambda x: x+3,
}[var](x)
方法三
通過定義類實現
參考Brian Beck通過類來實現Swich-case
# 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
# 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, it'll 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 nno 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 nno what c was!"
# Since Pierre's suggestion is backward-compatible with the original recipe,
# I have made the necessary modification to allow for the above usage.
查看Python官方:PEP 3103-A Switch/Case Statement
發現其實實現Switch Case需要被判斷的變數是可哈希的和可比較的,這與Python倡導的靈活性有沖突。在實現上,優化不好做,可能到最後最差的情況匯編出來跟If Else組是一樣的。所以Python沒有支持。