当前位置:首页 » 编程语言 » pythonswitch字典

pythonswitch字典

发布时间: 2023-05-15 12:20:53

‘壹’ 如何理解 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来解决某个问题, 并且每种情况下的操作在形式上是相同的(如都执行某个函数并且这些函数有
相同的参数), 就可以用这种方法来实现.

热点内容
流量漂移算法 发布:2025-07-17 08:36:19 浏览:746
ftp命令文件夹是否存在 发布:2025-07-17 08:35:19 浏览:170
java网络程序 发布:2025-07-17 08:33:44 浏览:617
用拼音编译代码 发布:2025-07-17 08:23:48 浏览:358
烽火服务器ip修改 发布:2025-07-17 08:14:43 浏览:981
c语言开机启动 发布:2025-07-17 08:12:09 浏览:440
天津开票系统服务器地址 发布:2025-07-17 08:11:01 浏览:696
大黄蜂BDftp 发布:2025-07-17 08:10:51 浏览:285
在QQ音乐上传 发布:2025-07-17 08:06:03 浏览:155
数据库关闭连接 发布:2025-07-17 08:05:10 浏览:189