第十四天学习:函数(2)

1、高阶函数

将函数当成参数传递的一种函数

#!/usr/bin/env python
def fun(x,y,f):
    return f(x)+f(y)
print(fun(-8,11,abs))
# python 7_4.py 
19

  

map()函数
格式:map(function, iterable, ...)
第一个参数为函数,第二个参数为可迭代对象
# cat 7_4.py 
#!/usr/bin/env python
li = [1,2,3,4,5]
def f(x):
    return x*x
print(map(f,li))
print(type(map(f,li)))
# python 7_4.py 
[1, 4, 9, 16, 25]
<type 'list'>

  

reduce()函数
语法:
reduce(function, iterable[, initializer])
  • function -- 函数,有两个参数
  • iterable -- 可迭代对象
  • initializer -- 可选,初始参数
# cat 7_4.py 
#!/usr/bin/e:nv python
def add(x,y):
    return x+y
print(reduce(add, [1,2,3,4,5]))
# python 7_4.py 
15

  

filter()函数
 
用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表
语法:filter(function, iterable)
  • function -- 判断函数。
  • iterable -- 可迭代对象
# cat 7_4.py 
#!/usr/bin/env python
def func(n):
    return n % 2 ==1
li= filter(func, [1,2,3,4,5,6,77,90])
print(li)
# python 7_4.py 
[1, 3, 5, 77]

  

sorted()
参考:http://www.runoob.com/python/python-func-sorted.html
对所有可迭代的对象进行排序操作
sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
语法:
sorted(iterable[, cmp[, key[, reverse]]])
  • iterable -- 可迭代对象。
  • cmp -- 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。
  • key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
  • reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)
>>>a = [5,7,6,3,4,1,2]
>>> b = sorted(a)       # 保留原列表
>>> a 
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]
 
>>> L=[('b',2),('a',1),('c',3),('d',4)]
>>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))   # 利用cmp函数
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> sorted(L, key=lambda x:x[1])               # 利用key
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
 
 
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2])            # 按年龄排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
 
>>> sorted(students, key=lambda s: s[2], reverse=True)       # 按降序
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>>

  

2、匿名函数
In [3]: m = lambda x,y:x+y
In [4]: m(3,6)
Out[4]: 9

  

原文地址:https://www.cnblogs.com/yshan13/p/7775191.html