中谷教育Python21~24笔记——switch和内联函数

来源:互联网 发布:物理仿真实验软件 编辑:程序博客网 时间:2024/04/27 20:37
1、首先,python并没有提供switch语句
2、python可以通过字典实现switch语句的功能。
   实现方法分为两步:
——首先,定义一个字典
——其次,调用字典的get()获取相应的表达式
3、例子
from __future__ import division 
def jia(x,y):
     return x + y
def jian(x,y):
     return x - y
def cheng(x,y):
     return x * y
def chu(x,y):
     return x / y
operator = {"+":jia,"-":jian,"*":cheng,"/":chu}
print (operator["+"])
print (jia)
print (chu(1,2))
print (operator["/"](1,2))
def f(x,o,y):
print (operator.get(o)(x,y))
def g(x,o,y):
print (operator.get(o,lambda x,y:x % y) (x,y)) 实现了default
g(100,'/',20)
g(100,'%',3)
4、例子的简写:
    from __future__ import division
        x = 1
        y = 2
        operator = "/"
        result = {"+":x + y,"-":x - y,"*":x * y,"/":x / y}
        print (result.get(operator))

中谷教育22~24——内建函数
abs()、max()、min()、len()、divmod()、pow()、round()、callable()、isinstance()、cmp()、range()、xrange()
类型转化函数:
type()、int()、long()、float()、complex()、str()、list()、tuple()、hex()、oct()、chr()、ord()
string函数
str.capitalize()
str.replace()
str.split()返回的是一个列表
或者是用导入模块的方式,用模块里的方法:譬如
import string
s = 'hello world'
string.replace(s,'hello','good')
序列函数
len()、max()、min()
filter(函数A,序列)当函数A对序列值为true时,保留序列的值
zip()用于几个列表的捆绑,并行遍历,所以选择最短的那个列表的长度为最后的长度
name = ['milo','zou','tom']
age = [20,30,40]
tel = ['133','233','333']
zip(name,age,tel)
[('milo',20,'133'),('zou','30','233'),('tom',40,'333')]
test = [1,2]
zip(name,age,tel,test)
[('milo',20,'133',1),('zou',30,'233',2)]

map()和zip差不多,第一个参数必须是None或函数,并行遍历,所以长度为最长,不足的地方用None填充
zip(None,name,age,tel,test)
[('milo',20,'133',1),('zou',30,'233',2),('tom',40,'333',None)]
a = [1,3,4]
b = [2,4,6]
def mf(x,y):
    return x * y
map(None,a,b)
[(1,2),(3,4),(5,6)]
map(mf,a,b)
[2,12,30]
reduce()

0 0