热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Python内置函数(转)

Python是一门很简洁,很优雅的语言,其很多内置函数结合起来使用,可以使用很少的代码来实现很多复杂的功能,如果同样的功能要让CC++Java来实现的话,可能会头大,其实Pytho

Python是一门很简洁,很优雅的语言,其很多内置函数结合起来使用,可以使用很少的代码来实现很多复杂的功能,如果同样的功能要让C/C++/Java来实现的话,可能会头大,其实Python是将复杂的数据结构隐藏在内置函数中,用C语言来实现,所以只要写出自己的业务逻辑Python会自动得出你想要的结果。这方面的内置函数主要有,filter,map,reduce,apply,结合匿名函数,列表解析一起使用,功能更加强大.使用内置函数最显而易见的好处是:

1. 速度快,使用内置函数,比普通的PYTHON实现,速度要快一倍左右。相当于C/C++的速度

2. 代码简洁

Buildin函数源码链接地址: (感兴趣的可以看看 ^_^)

https://hg.python.org/cpython/file/57c157be847f/Python/bltinmodule.c 

https://docs.python.org/3.3/library/functions.html

filter:

语法:

  1. >>> help(filter)  
  2. Help on built-in function filter in module __builtin__:  
  3.   
  4. filter(...)  
  5.     filter(function or None, sequence) -> list, tuple, or string  
  6.   
  7.     Return those items of sequence for which function(item) is true.  If  
  8.     function is Nonereturn the items that are true.  If sequence is a tuple  
  9.     or string, return the same type, else return a list.  

用途:

用于过滤与函数func()不匹配的值, 类似于SQL中select value != 'a'

相当于一个迭代器,调用一个布尔函数func来迭代seq中的每个元素,返回一个是bool_seq返回为True的序列

>>>第一个参数: function or None, 函数或None

>>>第二个参数: sequence,序列

说明:

>>>如果第一个参数为function,那么返回条件为真的序列(列表,元祖或字符串)

>>>如果第一个参数为None的话,那么返回序列中所有为True的项目

例1: 要过滤掉所有值为False的列表

  1. print filter(None,[-2,0,2,'',{},()])     #输出[-2,2],其余的都为False  

例2: 过滤某个字母

  1. >>> filter(lambda x: x !='a','abcd')  
  2. 'bcd'  
例3: 过滤字母以B开头的人名
  1. >>> names = ['Alice','Bob','Smith','David','Barbana']  
  2. >>> filter(lambda x: x.startswith('B'),names)  
  3. ['Bob''Barbana']  
例4: 过滤fib列表中的奇数,偶数项
  1. >>> fib = [0,1,1,2,3,5,8,13,21]  
  2. >>> filter(lambda x: x%2,fib)   #实际上等同于x%2 == 1的项才过滤  
  3. [11351321]  
  4. >>> filter(lambda x: x%2 ==0,fib)  
  5. [028]  
例5: 将2-20间所有质数列出来
  1. >>> filter(lambda x: not [x for i in range(2,x) if x%i == 0],range(2,20))  
  2. [235711131719]  
例6: 过滤人名为空的序列
  1. >>> names = ['Alice','Jerry','Sherry','Bob','Tom','']  
  2. >>> filter(None,names)  
  3. ['Alice''Jerry''Sherry''Bob''Tom']  
例7: 过滤某目录下所有以test.py结尾的文件
  1. import os,re                                 #需要的模块  
  2. files = os.listdir(r'D:\python')             #列出需要查找的目录的所有文件  
  3. test  = re.compile('test.py$',re.IGNORECASE) #re.IGNORECASE忽略大小写  
  4. print filter(test.search,files)              #过滤所有满足条件的文件  
  5.   
  6. >>>   
  7. ['1test.py''test.py']  
例8: 过滤所有子列表中,单词为'Python'的
  1. def filter_word(word):  
  2.   try:  
  3.     return word != 'Python'  
  4.   except ValueError:  
  5.     return False  
  6.   
  7. words = [['Perl','Python','Shell'],['Java','C/C++'],['VB','Dephi']]  
  8.   
  9. print [filter(filter_word,word) for word in words]  
  10. #用了列表解析的方法  

filter的逻辑实现:

  1. def filter(func,seq):  
  2.     f_seq = []                         #建一个空序列,用于存储过滤后的元素  
  3.     for item in seq:                   #对序列中的每个元素进行迭代  
  4.         if func(item):                 #如果为真的话  
  5.             f_seq.append(item)         #满足条件者,则加入  
  6.     return f_seq                       #返回过滤后的元素  
  7.   
  8. print filter(lambda x: x> 0,[-2,02]) #对匿名函数进行过滤,返回正值  
  9. >>>  
  10. [2]  
map:
  1. >>> help(map)  
  2. Help on built-in function map in module __builtin__:  
  3.   
  4. map(...)  
  5.     map(function, sequence[, sequence, ...]) -> list  
  6.   
  7.     Return a list of the results of applying the function to the items of  
  8.     the argument sequence(s).  If more than one sequence is given, the  
  9.     function is called with an argument list consisting of the corresponding  
  10.     item of each sequence, substituting None for missing values when not all  
  11.     sequences have the same length.  If the function is Nonereturn a list of  
  12.     the items of the sequence (or a list of tuples if more than one sequence).  
用途:

>>>对一个及多个序列执行同一个操作,返回一个列表

说明:

1. 返回一个列表,该列表是参数func对seq1,seq2处理的结果集

2. 可以有多个序列,如果函数为None的话,返回一个序列的列表

例1:常规用法

  1. >>> map(lambda x: x+1,[1,2,3,4])  
  2. [2345]  
  3. >>> map(lambda x,y: x+y,[1,2,3,4],(10,20,30,40))  
  4. [11223344]  
  5. >>> map(lambda x,y: x+y if y else x+10,[1,2,3,4,5],(1,2,3,4))  
  6. #第一个序列中的第五个元素存在,但在第二个序列中不存在,所以y为False,所以执行5+10  
  7. [246814]  
  8. >>> map(None,[1,2,3,4,5],(1,2))  #如果是None的话,以None来补齐短序列造成的空缺  
  9. [(11), (22), (3None), (4None), (5None)]  
  10. >>> names = ['Alice','Jerry','Bob','Barbar']  
  11. >>> map(len,names)               #求列表中每个元素的长度  
  12. [5536]  
  13. >>> m = [1,4,7]  
  14. >>> n = [2,5,8]  
  15. >>> map(None,m,n)  
  16. [(12), (45), (78)]  
  17. >>> import operator               #比较两个列表中元素大小  
  18. >>> a = [1,2,3]  
  19. >>> b = [0,4,9]  
  20. >>> map(operator.gt,a,b)  
  21. [TrueFalseFalse]  
例2: 求0-5之间数,[本身,平方,立方],如:元素2,则返回:[2,4,8]
  1. def func1(x): return x                   #返回自身  
  2. def func2(x): return x ** 2              #返回平方  
  3. def func3(x): return x ** 3              #返回立方  
  4.   
  5. funcs = [func1,func2,func3]              #函数列表  
  6.   
  7. for i in range(5):                       #遍历列表  
  8.     print map(lambda func: func(i),funcs)#对其中每个元素执行func1(i),func2(i),func3(i)操作  
例3: 实现下面的逻辑结构

1.0 [1,2,3,4,5]

2.0 [1,2,3,4,5]

....

  1. foos = [1.0,2.0,3.0,4.0,5.0]  
  2. bars = [1,2,3,4,5]  
  3.   
  4.   
  5. def test(foo):  
  6.     print foo,bars  
  7.   
  8.   
  9. print map(test,foos)  

例4: 用map函数实现下面的业务逻辑

s = [50,62,15,76,57,97,82,99,45,23]
'''
Require: print the grade from s as belows:
grage<60  - E
grade<70  - D
grade<80  - C
grade<90  - B
grage>90  - A
'''

  1. s = [50,62,15,76,57,97,82,99,45,23]  
  2.   
  3. def grage(x):  
  4.     try:  
  5.         if x < 60:  
  6.             return 'E'  
  7.         else:  
  8.             if   x < 70:  
  9.                 return 'D'  
  10.             elif x < 80:  
  11.                 return 'C'  
  12.             elif x < 90:  
  13.                 return 'B'  
  14.             else:  
  15.                 return 'A'  
  16.     except ValueError:  
  17.         print 'Input error, x should be int!'  
  18.   
  19. li = map(lambda x: "{0}-{1}".format(x,grage(x)),s) #对输出进行格式化处理  
  20.   
  21. for i in li:                                       #对生成的列表进行遍历  
  22.     print i  
  23.   
  24. >>>   
  25. 50-E  
  26. 62-D  
  27. 15-E  
  28. 76-C  
  29. 57-E  
  30. 97-A  
  31. 82-B  
  32. 99-A  
  33. 45-E  
  34. 23-E  

map的逻辑实现:

  1. def map(func,seq):  
  2.     map_seq = []                      #建空序列  
  3.     for item in seq:                  #对序列中每个元素进行处理  
  4.         map_seq.append(func(item))    #往空序列中添加func处理过的元素  
  5.     return map_seq                    #返回最后的列表  
  6.   
  7. print map(lambda x: x * 2,[1,2,3,4])  #[2,4,6,8]  
reduce:

用途:

func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值:如果初始值init给定,第一个比较会是init和第一个序列元素而不是序列的头两个元素。

说明:

1. 在Python3.0里面必须导入functools模块,from functools import reduce

2. reduce返回的必然是一个值,可以有初始值.

  1. >>> help(reduce)  
  2. Help on built-in function reduce in module __builtin__:  
  3.   
  4. reduce(...)  
  5.     reduce(function, sequence[, initial]) -> value  
  6.   
  7.     Apply a function of two arguments cumulatively to the items of a sequence,  
  8.     from left to right, so as to reduce the sequence to a single value.  
  9.     For example, reduce(lambda x, y: x+y, [12345]) calculates  
  10.     ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items  
  11.     of the sequence in the calculation, and serves as a default when the  
  12.     sequence is empty.  

例子:

>>> reduce(lambda x,y: x+y, [47,11,42,13])
113

其实现过程如下图所示:


NOTE: 

1. func()函数不能为None,否则报错

  1. >>> reduce(None,[1,2,3,4])  
  2. Traceback (most recent call last):  
  3.   File "", line 1in   
  4. TypeError: 'NoneType' object is not callable  
2. func(x,y)只能有两个参数,否则报错:
  1. >>> reduce(lambda x,y,z: x+y+z, [1,2,3,4],9)  
  2. Traceback (most recent call last):  
  3.   File "", line 1in   
  4. TypeError: <lambda>() takes exactly 3 arguments (2 given)  
reduce的逻辑实现:
  1. def reduce(func,seq,init=None):  
  2.     l_seq = list(seq)                  #先转为列表  
  3.     if init is None:                   #如果初始值  
  4.         res = l_seq.pop(0)  
  5.     else:  
  6.         res = init  
  7.   
  8.     for item in l_seq:  
  9.         res = func(res,item)           #func(res,item)作为结果集传给res  
  10.   
  11.     return res                         #返回结果集  
  12. print reduce(lambda x,y:x+y,[1,2,3,4]) #结果为10  
  13. print reduce(lambda x,y:x+y,[1,2,3,4],10)     #结果为20,init初始值为10  
apply:

语法:

  1. >>> help(apply)  
  2. Help on built-in function apply in module __builtin__:  
  3.   
  4. apply(...)  
  5.     apply(object[, args[, kwargs]]) -> value  
  6.   
  7.     Call a callable object with positional arguments taken from the tuple args,  
  8.     and keyword arguments taken from the optional dictionary kwargs.  
  9.     Note that classes are callable, as are instances with a __call__() method  
  10.   
  11.     Deprecated since release 2.3. Instead, use the extended call syntax:  
  12.         function(*args, **keywords).  

用途:

>>>当一个函数的参数存在于一个元组或者一个字典中时,用来间接的调用这个函数,元组或者字典中的参数按照顺序传递

说明:

1. args是一个包含按照函数所需参数传递的位置参数的一个元组,假如func(a=1,b=2),那么这个元组中就必须严格按照这个参数的位置顺序进行传递(a=3,b=4),而不能是(b=4,a=3)这样的顺序

2. kwargs是一个包含关键字参数的字典,而其中args如果不传递,kwargs需要传递,则必须在args的位置留空

3. apply函数的返回值就是func函数的返回值.

4. 其实apply(func,args,kwargs)从Python2.3开始,已经被func(*args,**kwargs)代替了.

例1: 常规使用

  1. def func1():               #无参函数  
  2.   print 'No Args!'  
  3.   
  4. def func2(arg1,arg2):      #两个参数  
  5.   print arg1,arg2  
  6.   
  7. def func3(arg1=1,arg2=2):  #带字典函数  
  8.   print arg1,arg2  
  9.   
  10. if __name__=='__main__':  
  11.   apply(func1)  
  12.   apply(func2,('Hello','World!'))  
  13.   apply(func3,(),{'arg1':'This is param1','arg2':'This is param2'})  #注意元祖参数为()  

既然可以用func(*args,**kwargs)来代替apply().那么apply有什么好处呢,几个看得见的好处,

1. 如果函数名,变量名太长的话,用apply()还是很方便的.

2. 如果不能确认有多少变量在args里面时,则必须使用apply,她能动态加载变量,及函数

  1. # Sorry about the long variable names ;-)  
  2.   
  3. args = function_returning_list_of_numbers()  
  4. func = function_returning_a_function_which_operates_on_a_list_of_numbers()  
  5.   
  6. # You want to do f(arg[0], arg[1], ...) but you don't know how many  
  7. # arguments are in 'args'.  For this you have to use 'apply':  
  8.   
  9. result = apply(func, args)  
3. 如果函数名作为一个对象来传递时,用apply()很方便
  1. def test(f,a,b):  
  2.     print 'test'  
  3.     print f(a,b)  
  4.   
  5. test(func,a,b)  
  6. #可以看出,test函数的第一个参数f就是一个函数对象。我们将func传递给f,  
  7. #那么test中的f()所做的实际上就是func()所实现的功能  
  8. #这样,我们就大大提供了程序的灵活性。假如我们我们有另外一个函数取代func,就可以使用相同的test函数  
  9. test(lambda x,y: x ** 2 + y,2,3)  
  10.   
  11. >>>   
  12. test  
  13. 7  
zip

  1. >>> help(zip)  
  2. Help on built-in function zip in module __builtin__:  
  3.   
  4. zip(...)  
  5.     zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]  
  6.   
  7.     Return a list of tuples, where each tuple contains the i-th element  
  8.     from each of the argument sequences.  The returned list is truncated  
  9.     in length to the length of the shortest argument sequence.  

用途:

>>>返回一个元祖列表,该元祖按顺序包含每个序列的相应元素,以最小的一个为准

说明:

>>>这个内置函数其实比较好理解,返回的对象就是一个元祖列表,看例子就好明白

例子:

  1. >>> zip(range(5),range(1,20,2))  
  2. [(01), (13), (25), (37), (49)]  
  3. >>> x=(1,2,3); y=(4,5);z=(6,)  
  4. >>> zip(x,y,z)  
  5. [(146)]  
zip的逻辑实现:
  1. def zip(*iterables):  
  2.     # zip('ABCD', 'xy') --> Ax By  
  3.     sentinel = object()  
  4.     iterators = [iter(it) for it in iterables]  
  5.     while iterators:  
  6.         result = []  
  7.         for it in iterators:  
  8.             elem = next(it, sentinel)  
  9.             if elem is sentinel:  
  10.                 return  
  11.             result.append(elem)  
  12.         yield tuple(result)  
可以参看这个综合例子:

http://www.360doc.com/content/14/0507/11/7821691_375450523.shtml

http://my.oschina.net/cloudcoder/blog/226461


推荐阅读
  • JavaScript实现表格数据的实时筛选功能
    本文介绍如何使用JavaScript实现对表格数据的实时筛选,帮助开发者提高用户体验。通过简单的代码示例,展示如何根据用户输入的关键字动态过滤表格内容。 ... [详细]
  • 本文介绍了如何利用JavaScript或jQuery来判断网页中的文本框是否处于焦点状态,以及如何检测鼠标是否悬停在指定的HTML元素上。 ... [详细]
  • 本文介绍了如何使用JQuery实现省市二级联动和表单验证。首先,通过change事件监听用户选择的省份,并动态加载对应的城市列表。其次,详细讲解了使用Validation插件进行表单验证的方法,包括内置规则、自定义规则及实时验证功能。 ... [详细]
  • 本文详细介绍了如何使用 Yii2 的 GridView 组件在列表页面实现数据的直接编辑功能。通过具体的代码示例和步骤,帮助开发者快速掌握这一实用技巧。 ... [详细]
  • 前言--页数多了以后需要指定到某一页(只做了功能,样式没有细调)html ... [详细]
  • 本文详细解析了Python中的os和sys模块,介绍了它们的功能、常用方法及其在实际编程中的应用。 ... [详细]
  • 本文探讨了如何在给定整数N的情况下,找到两个不同的整数a和b,使得它们的和最大,并且满足特定的数学条件。 ... [详细]
  • 从 .NET 转 Java 的自学之路:IO 流基础篇
    本文详细介绍了 Java 中的 IO 流,包括字节流和字符流的基本概念及其操作方式。探讨了如何处理不同类型的文件数据,并结合编码机制确保字符数据的正确读写。同时,文中还涵盖了装饰设计模式的应用,以及多种常见的 IO 操作实例。 ... [详细]
  • 本文介绍了在Windows环境下使用pydoc工具的方法,并详细解释了如何通过命令行和浏览器查看Python内置函数的文档。此外,还提供了关于raw_input和open函数的具体用法和功能说明。 ... [详细]
  • 本文介绍了Java并发库中的阻塞队列(BlockingQueue)及其典型应用场景。通过具体实例,展示了如何利用LinkedBlockingQueue实现线程间高效、安全的数据传递,并结合线程池和原子类优化性能。 ... [详细]
  • 在给定的数组中,除了一个数字外,其他所有数字都是相同的。任务是找到这个唯一的不同数字。例如,findUniq([1, 1, 1, 2, 1, 1]) 返回 2,findUniq([0, 0, 0.55, 0, 0]) 返回 0.55。 ... [详细]
  • 深度学习理论解析与理解
    梯度方向指示函数值增加的方向,由各轴方向的偏导数综合而成,其模长表示函数值变化的速率。本文详细探讨了导数、偏导数、梯度等概念,并结合Softmax函数、卷积神经网络(CNN)中的卷积计算、权值共享及池化操作进行了深入分析。 ... [详细]
  • 解决Element UI中Select组件创建条目为空时报错的问题
    本文介绍如何在Element UI的Select组件中使用allow-create属性创建新条目,并处理创建条目为空时出现的错误。我们将详细说明filterable属性的必要性,以及default-first-option属性的作用。 ... [详细]
  • 解析SQL查询结果的排序问题及其解决方案
    本文探讨了为什么某些SQL查询返回的数据集未能按预期顺序排列,并提供了详细的解决方案,帮助开发者理解并解决这一常见问题。 ... [详细]
  • C语言基础入门:7个经典小程序助你快速掌握编程技巧
    本文精选了7个经典的C语言小程序,旨在帮助初学者快速掌握编程基础。通过这些程序的实践,你将更深入地理解C语言的核心概念和语法结构。 ... [详细]
author-avatar
云海雨岛
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有