例一:
def f(x,y):
return x*y
print f(2,3)
g=lambda x,y:x*y
print g(1,2)
例二:def f(n):
if n>0:
n*f(n-1)
print f(5)
结果:TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
l=range(1,6)
def f(x,y):
return x*y
print reduce(f,l)
引入函数:reduce
改进版:print reduce(lambdax,y:x*y,l)
Switch语句:
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}
def f(x,o,y):
print operator.get(o)(x,y)
f(3,'+',2)
内置函数:len()长度:
print divmod(5,2)
结果:(2,1)
print isinstance(l,list)#判断类型
print cmp('hello','h')#判断字符串是否相等
print tuple(l)#类型的转化
字符串处理函数:
例一:s='hello world'
print s
print str.capitalize(s)#首字母大写
print s.replace("hello",'good')#代替函数
ss='123123123'
print ss.replace('1','x',2)
ip='192.168.123.52'
print ip.split('.',2)#切割函数
结果:hello world
Hello world
good world
x23x23123
['192', '168', '123.52']
序列处理函数:
例二:
a=[1,3,5]
b=[2,4,6]
def mf(x,y):
return x*y
print map(None,a,b)
print map(mf,a,b)
结果:[(1, 2), (3, 4), (5, 6)]
[2, 12, 30]
例三:print zip(name,age,tel)
print map(None,name,age,tel)
结果:[('milo', 20, '133'), ('zou', 30, '123'), ('tom', 40, '456')]
[('milo', 20, '133'), ('zou', 30, '123'), ('tom', 40, '456')]
例四:l=range(1,101)
def rf(x,y):
return x+y
print reduce(rf,l)
结果:5050
例五:
print filter(lambdax:x%2==0,l)
取出偶数