Python內置函數(轉)

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 "<stdin>", line 1in <module>  
  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 "<stdin>", line 1in <module>  
  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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章