标签:内建函数 第十四 func rabl 指定 原来 ever abs 比较
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
# 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‘>
# 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
# 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]
>>>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)] >>>
In [3]: m = lambda x,y:x+y In [4]: m(3,6) Out[4]: 9
标签:内建函数 第十四 func rabl 指定 原来 ever abs 比较
原文地址:http://www.cnblogs.com/yshan13/p/7775191.html