python入门(五)函数的定义

python中函数的定义
以def开头,后面跟函数定义的名称和())‘括号中定义参数’ 以冒号开始,并且进行缩放,return结束
如:

 def  hello (ming):
         print ming
         return 

传递参数:

ming=[1,2,3]
ming="ok"
如上所示,变量是没有类型的,可以为list可以为str
参数分为

必备参数
关键字参数
默认参数
不定长参数

必备参数:

 def  hello (ming):
         print ming
         return 

调用函数
hello();

那么会报错

关键字参数:

 def  hello (ming):
         print ming
         return 

调用函数
hello(ming="ok");

输出就是ok

缺省函数:

 def  hello (n,m=10):
         print n
         print m

调用函数
hello(n=20,m=20);
hello(n=100

返回值
n=20 m=20
n=100 m=10
不定长参数:

 def  hello (*args):
         print args
         return 

调用函数
hello(1);
hello(1,2,3,4)

输出
1
1,2,3,4
匿名函数:

正常函数:
 def  hello (n,m):
         print n*m
匿名函数:
lambda n,m:n*m

多个形参:

 def  hello (a,*args,**kwargs):
         print args
         return 

调用函数
hello(1,2,3,4,n=1,m=2)

输出:
1
(2,3,4)
{n:1,m:2}
高阶函数:

map是计算乘积的高阶函数
def hello(x):
    print x * x

map(hello,[1,2,3,4])
输出相同:
1,4,9,16
reduce是计算累计的高阶函数
def hi (x,y):
    print x+y
reduce(hi,[1,2,3,4])
    输出同样一样:
15

SORTED排序是高阶函数中用的比较多的

n = [5,7,6,3,4,1,2]
 m = sorted(n)      
print n
[5, 7, 6, 3, 4, 1, 2]
 print m
[1, 2, 3, 4, 5, 6, 7]
 A=dict(a=1,c=2,b=3,d=4)
如果我们直接排序
print(sorted(A))
['a', 'b', 'c', 'd']
 print(sorted(A.item(), key=lambda x:x[1]) )           
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
按倒叙排序
 print(sorted(A.item(), key=lambda x:x[1],reverse=True) )    
 [('d', 4), ('b', 3), ('c', 2), ('a', 1)]

猜你喜欢

转载自blog.51cto.com/13654063/2104174