Python笔记(17)-高阶函数

对于函数的理解

min函数可以求最小值;

In [1]: min(1,3,55,4)
Out[1]: 1

min函数赋值给变量a;

In [2]: a=min

In [3]: a
Out[3]: <function min>

查看a,它的类型为函数,由此可见函数其实也是变量

内置高阶函数

map函数

对一组数据所有元素依次做一个函数内定义的操作

[root@centos01 python]# cat map_test.py 
#!/usr/bin/env python
# coding:utf-8
def fun(x):
    return x**2

print map(fun,[1,2,3,4])
[root@centos01 python]# python map_test.py 
[1, 4, 9, 16]

reduce函数

必须是两个变量,逐个对后面放的一组元素做函数中定义的操作

[root@centos01 python]# cat reduce_test.py 
# coding:utf-8
#description:求10的阶乘
def fun(x,y):
    return x*y

print reduce(fun,range(1,11))
[root@centos01 python]# python reduce_test.py 
3628800

filter函数

将一组数据中的元素逐个带入fun()函数判断,如果为真就输出这个元素,否则不输出

[root@centos01 python]# cat filter_test.py 
# coding:utf-8
#description:找出0~10之间所有的偶数
def fun(x):
    return x%2==0

print filter(fun,range(11))
[root@centos01 python]# python filter_test.py 
[0, 2, 4, 6, 8, 10]

sorted函数

按照函数中定义的内容对一组数据进行排序

直接使用sorted排序,由于是以ASCII码表进行排序的,与我们平时认为的排序结果不大相同:

In [4]: sorted(["alic","Alex","bon","Hello","Wee"])
Out[4]: ['Alex', 'Hello', 'Wee', 'alic', 'bon']

因此,可以先把元素都转换为大写,在进行排序,就与我们平时所认为的排序方式一致了:

[root@centos01 python]# cat sorted_test.py 
# coding:utf-8
def fun(x,y):
    s1=x.upper()  #将字符串转换为大写
    s2=y.upper()
    return 0  #使用比较函数必须要有返回值,否则报错,所以这里随便给一个返回值

print sorted(["alic","Alex","bon","Hello","Wee"],fun)  #在这几个内置高阶函数里面,sorted在使用的时候是唯一一个将函数名放到一组数据后面进行使用的
[root@centos01 python]# python sorted_test.py 
['alic', 'Alex', 'bon', 'Hello', 'Wee']

sorted key方法:

可以以一个关键字所包含的元素进行排序

In [5]: goods=[["apple",2,20],["book",5,90],["fish",3,30]]   #一个列表里面还有三个列表
In [6]: def min_one(x):        #函数作用:返回列表里的第三个元素
   ...:     return x[2]
   ...: 
In [7]: sorted(goods,key=min_one)    #以每个列表里面第三个元素为关键字进行sorted排序
Out[7]: [['apple', 2, 20], ['fish', 3, 30], ['book', 5, 90]]
In [8]: sorted(goods,key=min_one)[0][0]    #从排序结果中输出第一个列表里的第一个元素
Out[8]: 'apple'

lambda匿名函数

对于一些简单函数可以不用写出一个完整的函数形式,可以用匿名函数代替,例如lambda x:x**2就相当于

def fun(x): 

  return x**2

[root@centos01 python]# cat lambda_test.py 
# coding:utf-8
print map(lambda x:x**2,[1,2,3,4])
print reduce(lambda x,y:x*y,range(1,11))
print filter(lambda x:x%2==0,range(11))
[root@centos01 python]# python lambda_test.py 
[1, 4, 9, 16]
3628800
[0, 2, 4, 6, 8, 10]

猜你喜欢

转载自www.cnblogs.com/vaon/p/11120820.html