首页 > 编程语言 > 详细

Python之内置函数

时间:2019-07-15 19:02:15      阅读:81      评论:0      收藏:0      [点我收藏+]

内置函数

技术分享图片

注:查看详细https://docs.python.org/3/library/functions.html#next

 匿名函数  

1 def calc(x):
2     return x+1
3 
4 
5 print(calc(10))
6 # print(lambda x:x+1)  # 匿名函数内存地址
7 
8 func = lambda x: x + 1
9 print(func(10))

高阶函数

1.map内置函数   map(func, *iterables) --> map object
技术分享图片
 1 num_l = [1, 2, 3, 4, 5, 6]
 2 # lambda x: x+1
 3 
 4 
 5 def add_one(x):
 6     return x+1
 7 
 8 
 9 def map_test(func, array):
10     """
11     模拟map内置函数
12     :param func: 传入的参数进行处理方法
13     :param array: 传入可迭代的对象
14     :return:
15     """
16     ret = []
17     for i in array:
18         res = func(i)
19         ret.append(res)
20     return ret
21 
22 
23 print(map_test(add_one, num_l))
24 print(map_test(lambda x: x+1, num_l))
25 res = map(lambda x: x+1, num_l)
26 print(list(res))
27 
28 
29 name = eric
30 v = map(lambda x: x.upper(), name).__iter__()   # 把对象转成可迭代对象 遵行迭代协议
31 r = v.__next__()  # next直到StopIteration
32 print(r)
33 
34 # print(list(map(lambda x: x.upper(), name)))
map

  2.filter函数

技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 
 5 movie_person = [eric_sb, alex_sb, lhf]
 6 
 7 
 8 def sb_show(x):
 9     return x.endswith(_sb)
10 
11 
12 def filter_test(func, array):
13     ret = []
14     for p in array:
15         if not func(p):
16             ret.append(p)
17     return ret
18 
19 
20 print(filter_test(sb_show, movie_person))
21 
22 print(list(filter(lambda x: not x.endswith(_sb), movie_person)))
filter

  3.reduce函数

技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 
 5 from functools import reduce
 6 
 7 num_l = [1, 2, 3, 100]
 8 
 9 
10 def reduce_test(func, array, init=None):
11     if init is None:
12         res = array.pop(0)
13     else:
14         res = init
15     for num in num_l:
16         res = func(res, num)
17     return res
18 
19 
20 # print(reduce_test(lambda x, y: x * y, num_l))
21 # reduce:处理一个序列,然后把序列合并操作
22 print(reduce(lambda x, y: x * y, num_l, 2))
23 
24 
25 def reduce(function, sequence, initial=None):  # real signature unknown; restored from __doc__
26     """
27     reduce(function, sequence[, initial]) -> value
28 
29     Apply a function of two arguments cumulatively to the items of a sequence,
30     from left to right, so as to reduce the sequence to a single value.
31     For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
32     ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
33     of the sequence in the calculation, and serves as a default when the
34     sequence is empty.
35     """
36     pass
reduce
 

Python之内置函数

原文:https://www.cnblogs.com/Alexephor/p/11190587.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!