pythonswitch字典
『壹』 如何理解 python中的switch
方法/步驟
1
我們以加減和一個隨意名字的函數來解析switch的用法,說白了也是很簡答嗎的。帆敬檔首先添加一個add的方法。
2
再添加一個相減的方法,同時加了print方便debug程序。
3
之後為了作對比,隨便寫稿虛了一個abc的方法。
4
建立一個字典,用『+』,『-』,『abc』分別作為key,對應相映的方法。
5
之後再加兩個方法,通過對於參數的調整,用字典的get『key』方法獲取函數,並且傳入參數。
6
試著用(1,『+』,5) 來實現1+5。
7
用(6,『-』,2) 來實現6-2,調用的都是同一個方法,態亂參數不同,通過字典key獲取到的函數也不同,這就是我所理解的switch的用法。
8
最後,隨便試一下,用『abc』也可以,哈哈。
http://jingyan..com/article/1e5468f90f7c65484961b715.html
『貳』 python中的字典實現switch功能
#coding:utf-8
from__future__importdivision
result={
'+':lambdax,y:x+y,
'-':lambdax,y:x-y,
'*':lambdax,y:x*y,
'/':lambdax,y:x/y,
}
x=raw_input("輸入第一個數字:")
z=raw_input("輸入運算符:")
y=raw_input("輸入第二個數字:")
print"=",result.get(z)(int(x),int(y))
『叄』 為什麼Python中沒有Switch/Case語句
同於我用過的其它編程語言,Python 沒有 switch / case 語句。為了實現它,我們可以使用字典映射:
這段代碼類似於:
Python 代碼通常比處理 case 的標准方法更為簡短,也可以說它更難理解。當我初次使用 Python 時,感覺很奇怪並且心煩意亂。而隨著時間的推移,在 switch 中使用字典的 key 來做標識符變得越來越習以為常。
函數的字典映射
在 Python 中字典映射也可以包含函數或者 lambda 表達式:
雖然zero和one中的代碼很簡單,但是很多 Python 程序使用這樣的字典映射來調度緩灶燃復雜的流程。
類的調度方法
如果在一辯猜個類中,不確定要使用哪種方法,可以用一個調度方法在運行的時候來確定。
很靈活,對吧?
官方說明
官方文檔的解釋說,「用if... elif... elif... else序列擾虛很容易來實現 switch / case 語句」。而且可以使用函數字典映射和類的調度方法。
『肆』 為什麼Python中沒有Switch/Case語句
因為作為一門解釋型語言,switch/case是沒有存在必要的,if/elif/else就可以實現的功能,為什麼要再提供重復的?
if else的得一個if一個if的判斷過去,如果匹配的是最後一個條件,前面所有if都得判斷一遍的。
看過匯編就知道,C語言的switch/case,在case值連續的時候,是可以根據case值直接計算該跳轉的地址的。
『伍』 python 如何根據輸入參數調用不同的函數
#Python3.x
deffunc():
c=input("PleaseEnteraChar:")
while(True):
ifc=='a':
func_a()
break;
ifc=='b':
func_b()
break;
func()
『陸』 Python中字典創建、遍歷、添加等實用操作技巧合集
欄位是Python是字典中唯一的鍵-值類型,是Python中非常重要的數據結構,因其用哈希的方式存儲數據,其復雜度為O(1),速度非常快。下面列出字典的常用的用途.
一、字典中常見方法列表
代碼如下:
#方法
#描述
-------------------------------------------------------------------------------------------------
D.clear()
#移除D中的所有項
D.()
#返回D的副本
D.fromkeys(seq[,val])
#返回從seq中獲得的鍵和被設置為val的值的字典。可做類方法調用
D.get(key[,default])
#如果D[key]存在,將其返回;否則返回給定的默認值None
D.has_key(key)
#檢查D是否有給定鍵key
D.items()
#返回表示D項的(鍵,值)對列表
D.iteritems()
#從D.items()返回的(鍵,值)對中返回一個可迭代的對象
D.iterkeys()
#從D的鍵中返回一個可迭代對象
D.itervalues()
#從D的值中返回一個可迭代對象
D.keys()
#返回D鍵的列表
D.pop(key[,d])
#移除並且返回對應給定鍵key或給定的默認值D的值
D.popitem()
#從D中移除任意一項,並將其作為(鍵,值)對返回
D.setdefault(key[,default])
#如果D[key]存在則將其返回;否則返回默認值None
D.update(other)
#將other中的每一項加入到D中。
D.values()
#返回D中值的列表
二、創建字典的五種方法
方法一:
常規方法
代碼如下:
#
如果事先能拼出整個字典,則此方法比較方便
>>>
D1
=
{'name':'Bob','age':40}
方法二:
動態創建
代碼如下:
#
如果需要動態地建立字典的一個欄位,則此方法比較方便
>>>
D2
=
{}
>>>
D2['name']
=
'Bob'
>>>
D2['age']
=
40
>>>
D2
{'age':
40,
'name':
'Bob'}
方法三:
dict--關鍵字形式
代碼如下:
#
代碼比較少,但鍵必須為字元串型。常用於函數賦值
>>>
D3
=
dict(name='Bob',age=45)
>>>
D3
{'age':
45,
'name':
'Bob'}
方法四:
dict--鍵值序列
代碼如下:
#
如果需要將鍵值逐步建成序列,則此方式比較有用,常與zip函數一起使用
>>>
D4
=
dict([('name','Bob'),('age',40)])
>>>
D4
{'age':
40,
'name':
'Bob'}
或
代碼如下:
>>>
D
=
dict(zip(('name','bob'),('age',40)))
>>>
D
{'bob':
40,
'name':
'age'}
方法五:
dict--fromkeys方法#
如果鍵的值都相同的話,用這種方式比較好,並可以用fromkeys來初始化
代碼如下:
>>>
D5
=
dict.fromkeys(['A','B'],0)
>>>
D5
{'A':
0,
'B':
0}
如果鍵的值沒提供的話,默認為None
代碼如下:
>>>
D3
=
dict.fromkeys(['A','B'])
>>>
D3
{'A':
None,
'B':
None}
三、字典中鍵值遍歷方法
代碼如下:
>>>
D
=
{'x':1,
'y':2,
'z':3}
#
方法一
>>>
for
key
in
D:
print
key,
'=>',
D[key]
y
=>
2
x
=>
1
z
=>
3
>>>
for
key,
value
in
D.items():
#
方法二
print
key,
'=>',
value
y
=>
2
x
=>
1
z
=>
3
>>>
for
key
in
D.iterkeys():
#
方法三
print
key,
'=>',
D[key]
y
=>
2
x
=>
1
z
=>
3
>>>
for
value
in
D.values():
#
方法四
print
value
2
1
3
>>>
for
key,
value
in
D.iteritems():
#
方法五
print
key,
'=>',
value
y
=>
2
x
=>
1
z
=>
3
Note:用D.iteritems(),
D.iterkeys()的方法要比沒有iter的快的多。
四、字典的常用用途之一代替switch
在C/C++/Java語言中,有個很方便的函數switch,比如:
代碼如下:
public
class
test
{
public
static
void
main(String[]
args)
{
String
s
=
"C";
switch
(s){
case
"A":
System.out.println("A");
break;
case
"B":
System.out.println("B");
break;
case
"C":
System.out.println("C");
break;
default:
System.out.println("D");
}
}
}
在Python中要實現同樣的功能,
方法一,就是用if,
else語句來實現,比如:
代碼如下:
from
__future__
import
division
def
add(x,
y):
return
x
+
y
def
sub(x,
y):
return
x
-
y
def
mul(x,
y):
return
x
*
y
def
div(x,
y):
return
x
/
y
def
operator(x,
y,
sep='+'):
if
sep
==
'+':
print
add(x,
y)
elif
sep
==
'-':
print
sub(x,
y)
elif
sep
==
'*':
print
mul(x,
y)
elif
sep
==
'/':
print
div(x,
y)
else:
print
'Something
Wrong'
print
__name__
if
__name__
==
'__main__':
x
=
int(raw_input("Enter
the
1st
number:
"))
y
=
int(raw_input("Enter
the
2nd
number:
"))
s
=
raw_input("Enter
operation
here(+
-
*
/):
")
operator(x,
y,
s)
方法二,用字典來巧妙實現同樣的switch的功能,比如:
代碼如下:
#coding=gbk
from
__future__
import
division
x
=
int(raw_input("Enter
the
1st
number:
"))
y
=
int(raw_input("Enter
the
2nd
number:
"))
def
operator(o):
dict_oper
=
{
'+':
lambda
x,
y:
x
+
y,
'-':
lambda
x,
y:
x
-
y,
'*':
lambda
x,
y:
x
*
y,
'/':
lambda
x,
y:
x
/
y}
return
dict_oper.get(o)(x,
y)
if
__name__
==
'__main__':
o
=
raw_input("Enter
operation
here(+
-
*
/):
")
print
operator(o)
『柒』 python中有switch嗎
python中沒有switch結構,一般用字典(dict)來模擬switch實現
『捌』 python 字典可以儲存函數嗎
Python中是沒有switch的, 所以有時我們需要用switch的用法, 就只能通過if else來實現了. 但if else寫起來比較冗長,
這時就可以使用Python中的dict來實現, 比switch還要簡潔. 用法如下:
如果是key1的情況就執行func1, 如果是key2的情況就執行func2...(func1, func2...所有的函數的參數形式需要相同),
假設各個函數參數均為(arg1, arg2):
dictName = {"key1":func1, "key2":func2, "key3":func3"...}#字典的值直接是函數的名字,不能加引號dictName[key](arg1, arg2)
示例代碼如下:
#!/usr/bin/python#File: switchDict.py#Author: lxw#Time: 2014/10/05import redef add(x, y): return x + ydef sub(x, y): return x - ydef mul(x, y): return x * ydef div(x, y): return x / ydef main():
inStr = raw_input("Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.\n")
inList = re.split("(\W+)", inStr)
inList[1] = inList[1].strip() print("-------------------------") print(inList) print("-------------------------") #Method 1:
if inList[1] == "+": print(add(int(inList[0]), int(inList[2]))) elif inList[1] == "-": print(sub(int(inList[0]), int(inList[2]))) elif inList[1] == "*": print(mul(int(inList[0]), int(inList[2]))) elif inList[1] == "/": print(div(int(inList[0]), int(inList[2]))) else: pass
#Method 2:
try:
operator = {"+":add, "-":sub, "*":mul, "/":div} print(operator[inList[1]](int(inList[0]), int(inList[2]))) except KeyError: passif __name__ == '__main__':
main()
Output:
PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.1 + 2
-------------------------['1', '+', '2']-------------------------
3
3PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.4 - 9
-------------------------['4', '-', '9']-------------------------
-5
-5PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.6 / 5
-------------------------['6', '/', '5']-------------------------
1
1PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.1 9 9
-------------------------['1', '', '9', ' ', '9']-------------------------PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.1 ( 9
-------------------------['1', '(', '9']-------------------------PS J:\>
個人感覺, 如果想用switch來解決某個問題, 並且每種情況下的操作在形式上是相同的(如都執行某個函數並且這些函數有
相同的參數), 就可以用這種方法來實現.