Python常用內建函數介紹【filter,map,reduce,apply,zip】,pythonreduce

來源:互聯網
上載者:User

Python常用內建函數介紹【filter,map,reduce,apply,zip】,pythonreduce

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 Falsewords = [['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,barsprint 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
'''

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-E62-D15-E76-C57-E97-A82-B99-A45-E23-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

其實現過程如所示:


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]) #結果為10print 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是一個包含關鍵字參數的字典,而其中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,arg2def func3(arg1=1,arg2=2):  #帶字典函數  print arg1,arg2if __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)>>> test7
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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.