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:

语法:

>>> help(filter)
Help on built-in function filter in module __builtin__: filter(...)
filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
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的列表

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

例2: 过滤某个字母

>>> filter(lambda x: x !='a','abcd')
'bcd'

例3: 过滤字母以B开头的人名

>>> names = ['Alice','Bob','Smith','David','Barbana']
>>> filter(lambda x: x.startswith('B'),names)
['Bob', 'Barbana']

例4: 过滤fib列表中的奇数,偶数项

>>> fib = [0,1,1,2,3,5,8,13,21]
>>> filter(lambda x: x%2,fib) #实际上等同于x%2 == 1的项才过滤
[1, 1, 3, 5, 13, 21]
>>> filter(lambda x: x%2 ==0,fib)
[0, 2, 8]

例5:
将2-20间全部质数列出来

>>> filter(lambda x: not [x for i in range(2,x) if x%i == 0],range(2,20))
[2, 3, 5, 7, 11, 13, 17, 19]

例6: 过滤人名为空的序列

>>> names = ['Alice','Jerry','Sherry','Bob','Tom','']
>>> filter(None,names)
['Alice', 'Jerry', 'Sherry', 'Bob', 'Tom']

例7: 过滤某文件夹下全部以test.py结尾的文件

import os,re                                 #须要的模块
files = os.listdir(r'D:\python') #列出须要查找的文件夹的全部文件
test = re.compile('test.py$',re.IGNORECASE) #re.IGNORECASE忽略大写和小写
print filter(test.search,files) #过滤全部满足条件的文件 >>>
['1test.py', 'test.py']

例8:
过滤全部子列表中,单词为'Python'的

def filter_word(word):
try:
return word != 'Python'
except ValueError:
return False words = [['Perl','Python','Shell'],['Java','C/C++'],['VB','Dephi']] print [filter(filter_word,word) for word in words]
#用了列表解析的方法

filter的逻辑实现:

def filter(func,seq):
f_seq = [] #建一个空序列,用于存储过滤后的元素
for item in seq: #对序列中的每一个元素进行迭代
if func(item): #假设为真的话
f_seq.append(item) #满足条件者,则增加
return f_seq #返回过滤后的元素 print filter(lambda x: x> 0,[-2,0, 2]) #对匿名函数进行过滤,返回正值
>>>
[2]

map:

>>> help(map)
Help on built-in function map in module __builtin__: map(...)
map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).

用途:

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

说明:

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

2. 能够有多个序列,假设函数为None的话,返回一个序列的列表

例1:常规使用方法

>>> map(lambda x: x+1,[1,2,3,4])
[2, 3, 4, 5]
>>> map(lambda x,y: x+y,[1,2,3,4],(10,20,30,40))
[11, 22, 33, 44]
>>> map(lambda x,y: x+y if y else x+10,[1,2,3,4,5],(1,2,3,4))
#第一个序列中的第五个元素存在,但在第二个序列中不存在,所以y为False,所以运行5+10
[2, 4, 6, 8, 14]
>>> map(None,[1,2,3,4,5],(1,2)) #假设是None的话,以None来补齐短序列造成的空缺
[(1, 1), (2, 2), (3, None), (4, None), (5, None)]
>>> names = ['Alice','Jerry','Bob','Barbar']
>>> map(len,names) #求列表中每一个元素的长度
[5, 5, 3, 6]
>>> m = [1,4,7]
>>> n = [2,5,8]
>>> map(None,m,n)
[(1, 2), (4, 5), (7, 8)]
>>> import operator #比較两个列表中元素大小
>>> a = [1,2,3]
>>> b = [0,4,9]
>>> map(operator.gt,a,b)
[True, False, False]

例2: 求0-5之间数,[本身,平方,立方],如:元素2,则返回:[2,4,8]

def func1(x): return x                   #返回自身
def func2(x): return x ** 2 #返回平方
def func3(x): return x ** 3 #返回立方 funcs = [func1,func2,func3] #函数列表 for i in range(5): #遍历列表
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]

....

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

例4: 结合map和filter,求0-10之间偶数的平方,汇合成列表

>>> map(lambda x:x**2, filter(lambda x: x%2==0,range(10)))
[0, 4, 16, 36, 64]

例5: 用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

'''

s = [50,62,15,76,57,97,82,99,45,23]

def grage(x):
try:
if x < 60:
return 'E'
else:
if x < 70:
return 'D'
elif x < 80:
return 'C'
elif x < 90:
return 'B'
else:
return 'A'
except ValueError:
print 'Input error, x should be int!' li = map(lambda x: "{0}-{1}".format(x,grage(x)),s) #对输出进行格式化处理 for i in li: #对生成的列表进行遍历
print i >>>
50-E
62-D
15-E
76-C
57-E
97-A
82-B
99-A
45-E
23-E

map的逻辑实现:

def map(func,seq):
map_seq = [] #建空序列
for item in seq: #对序列中每一个元素进行处理
map_seq.append(func(item)) #往空序列中加入func处理过的元素
return map_seq #返回最后的列表 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返回的必定是一个值,能够有初始值.

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

样例:

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

113

事实上现步骤例如以下图所看到的:

事实上现过程等同以下的:

>>> import operator
>>> reduce(operator.add,[47,11,42,13])
113

NOTE: 

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

>>> reduce(None,[1,2,3,4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

2. func(x,y)仅仅能有两个參数,否则报错:

>>> reduce(lambda x,y,z: x+y+z, [1,2,3,4],9)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 3 arguments (2 given)

reduce的逻辑实现:

def reduce(func,seq,init=None):
l_seq = list(seq) #先转为列表
if init is None: #假设初始值
res = l_seq.pop(0)
else:
res = init for item in l_seq:
res = func(res,item) #func(res,item)作为结果集传给res return res #返回结果集
print reduce(lambda x,y:x+y,[1,2,3,4]) #结果为10
print reduce(lambda x,y:x+y,[1,2,3,4],10) #结果为20,init初始值为10

apply:

语法:

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

用途:

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

说明:

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

2. kwargs是一个包括keyword參数的字典,而当中args假设不传递,kwargs须要传递,则必须在args的位置留空

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

4. 事实上apply(func,args,kwargs)从Python2.3開始,已经被func(*args,**kwargs)取代了.

例1: 常规使用

def func1():               #无參函数
print 'No Args!' def func2(arg1,arg2): #两个參数
print arg1,arg2 def func3(arg1=1,arg2=2): #带字典函数
print arg1,arg2 if __name__=='__main__':
apply(func1)
apply(func2,('Hello','World!'))
apply(func3,(),{'arg1':'This is param1','arg2':'This is param2'}) #注意元祖參数为()

既然能够用func(*args,**kwargs)来取代apply().那么apply有什么优点呢,几个看得见的优点,

1.
假设函数名,变量名太长的话,用apply()还是非常方便的.

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

# Sorry about the long variable names ;-)

args = function_returning_list_of_numbers()
func = function_returning_a_function_which_operates_on_a_list_of_numbers() # You want to do f(arg[0], arg[1], ...) but you don't know how many
# arguments are in 'args'. For this you have to use 'apply': result = apply(func, args)

3.
假设函数名作为一个对象来传递时,用apply()非常方便

def test(f,a,b):
print 'test'
print f(a,b) test(func,a,b)
#能够看出,test函数的第一个參数f就是一个函数对象。我们将func传递给f,
#那么test中的f()所做的实际上就是func()所实现的功能
#这样,我们就大大提供了程序的灵活性。假如我们我们有另外一个函数代替func,就能够使用同样的test函数
test(lambda x,y: x ** 2 + y,2,3) >>>
test
7

zip

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

用途:

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

说明:

>>>这个内置函数事实上比較好理解,返回的对象就是一个元祖列表,看样例就好明确

样例:

>>> zip(range(5),range(1,20,2))
[(0, 1), (1, 3), (2, 5), (3, 7), (4, 9)]
>>> x=(1,2,3); y=(4,5);z=(6,)
>>> zip(x,y,z)
[(1, 4, 6)]

zip的逻辑实现:

def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)

能够參看这个综合样例:

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

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

Python经常使用内置函数介绍【filter,map,reduce,apply,zip】的更多相关文章

  1. Python内置函数之filter map reduce

    Python内置函数之filter map reduce 2013-06-04 Posted by yeho Python内置了一些非常有趣.有用的函数,如:filter.map.reduce,都是对 ...

  2. python之有用的3个内置函数(filter/map/reduce)

    这三个内置函数还是非常有用的,在工作中用的还不少,顺手,下面一一进行介绍 1.filter 语法:filter(function,iterable) 解释:把迭代器通过function函数进行过滤出想 ...

  3. Python学习(五)函数 —— 内置函数 lambda filter map reduce

    Python 内置函数 lambda.filter.map.reduce Python 内置了一些比较特殊且实用的函数,使用这些能使你的代码简洁而易读. 下面对 Python 的 lambda.fil ...

  4. Python的常用内置函数介绍

    Python的常用内置函数介绍 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.取绝对值(abs) #!/usr/bin/env python #_*_coding:utf-8_ ...

  5. 内置函数--sorted,filter,map

    sorted() 排序函数. 语法: sorted(Iterable, key=None, reverse=False) Iterable: 可迭代对象;  key: 排序规则(排序函数); reve ...

  6. Python常用内置函数介绍

    Python提供了一个内联模块buildin.内联模块定义了一些开发中经常使用的函数,利用这些函数可以实现数据类型的转换.数据的计算.序列的处理等功能.下面将介绍内联模块中的常用函数. Python内 ...

  7. python学习交流 - 内置函数使用方法和应用举例

    内置函数 python提供了68个内置函数,在使用过程中用户不再需要定义函数来实现内置函数支持的功能.更重要的是内置函数的算法是经过python作者优化的,并且部分是使用c语言实现,通常来说使用内置函 ...

  8. Python3的内置函数介绍

    Python3的官网链接:https://docs.python.org/3/library/functions.html?highlight=built#ascii 内置函数介绍 abs 绝对值函数 ...

  9. python常用的内置函数哈哈

    python常用的内置函数集合做一个归类用的时候可以查找 abs 返回数字x的绝对值或者x的摸 all (iterable)对于可迭代的对象iterable中所有元素x都有bool(x)为true,就 ...

随机推荐

  1. hive SQL优化之distribute by和sort by

    近期在优化hiveSQL. 以下是一段排序,分组后取每组第一行记录的SQL INSERT OVERWRITE TABLE t_wa_funnel_distinct_temp PARTITION (pt ...

  2. [TypeStyle] Reusable styles using TypeStyle mixins

    TypeStyle’s style function allows you to give multiple objects as an argument. This provides a simpl ...

  3. C# .NET Socket

    C# .NET Socket 简单实用框架 背景: 首先向各位前辈,大哥哥小姐姐问一声好~ 这是我第一次写博客,目前为一个即将步入大四的学生,上学期在一家公司实习了半年,后期发现没有动力,而且由于薪水 ...

  4. linux下FAT32格式u盘只读的问题及解决方法

    以下是网上看到的解决办法:http://blog.csdn.net/heqiuya/article/details/7870554 其实是掉电保护,之前挂在的SD变成了制度文件,只需要将SD卡重新挂载 ...

  5. php 随机数中奖demo演示

    感谢https://blog.csdn.net/z960339491/article/details/69511491提供的思路,应该是java,于我不合适,写了php <?php // 中奖概 ...

  6. composer 安装 laravel 更换下载源

    1.在确认cmd 下载好composer 2. composer -V 3. composer config -g repo.packagist composer https://packagist. ...

  7. angular表单的使用实例

    原文 https://www.jianshu.com/p/da1fd5396798 大纲 1.模板驱动表单的创建 2.响应式表单的创建 3.模板驱动型表单的自定义指令 4.响应式表单的自定义指令 5. ...

  8. ios开发网络学习AFN三:AFN的序列化

    #import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...

  9. iOS开发AFN使用二:AFN文件下载与文件上传

    #import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...

  10. 【C++竞赛 C】yyy的数学公式

    时间限制:1s 内存限制:32MB 问题描述 yyy遇到了一个数学问题如下: S_n=∑F(i) 其中F(i)表示i的最大奇因数 yyy的数学非常好,很快就得到了结果.现在他把问题交给你,你能解决吗? ...