Python中有許多功能豐富的內置函數,本文基於Python 2.7,就經常使用的一些函數的典型用法作一些積累,不斷更新中。python
# coding:utf-8 # sorted函數的三種用法 from operator import itemgetter data1 = [{'aa':22,'bb':11},{'aa':12,'cc':23},{'aa':67,'dd':103}] data2 = [{'age':18,'name':'Tom'},{'age':10,'name':'Tim'},{'age':30,'name':'John'},{'age':18,'name':'Amy'}] def sort1(): # 對data1依據'aa'字段值的大小從小打到排序 ret = sorted(data1,key = lambda item:item['aa']) # 注:若是這裏的key寫'bb'或'cc',會報KeyError,由於這兩個屬性並非每一個元素都有的 print ret # 輸出: ''' [{'aa': 12, 'cc': 23}, {'aa': 22, 'bb': 11}, {'aa': 67, 'dd': 103}] ''' def sort2(): # 對data1依據'aa'字段值的大小從小打到排序 ret = sorted(data1,cmp = lambda x,y:cmp(x['aa'],y['aa'])) print ret # 輸出: ''' [{'aa': 12, 'cc': 23}, {'aa': 22, 'bb': 11}, {'aa': 67, 'dd': 103}] ''' def sort3(): # 使用itemgetter對data1依據'aa'字段值的大小從小打到排序 ret = sorted(data1,key = itemgetter('aa')) print ret # 輸出: ''' [{'aa': 12, 'cc': 23}, {'aa': 22, 'bb': 11}, {'aa': 67, 'dd': 103}] ''' def sort4(): # 對data2進行排序,先按照'age'從小到大排序,'age'相同的狀況下,再按照'name'排序 ret = sorted(data2,key = itemgetter('age','name')) print ret # 輸出: ''' [{'age': 10, 'name': 'Tim'}, {'age': 18, 'name': 'Amy'}, {'age': 18, 'name': 'Tom'}, {'age': 30, 'name': 'John'}] '''
# coding:utf-8 # 執行命令行命令的三種方式 import os import commands command = 'ls -al /root' def method1(): ''' 方式1 ''' os.system(command) # 執行結果:返回執行狀態碼 def method2(): ''' 方式2 ''' out1 = os.popen(command) print out1.read() # 輸出:執行結果字符串 def method3(): ''' 方式3 ''' (status,out) = commands.getstatusoutput(command) # 輸出:status是執行狀態碼,out是執行結果字符串
Docstring: 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函數的文檔,從文檔中能夠看出,zip函數接收1個或多個序列做爲參數,返回一個由元組組成的列表。app
結果列表的第i個元素是seq1~seqn的第i個元素組成的元組。函數
結果列表的長度等於seq1~seqn中最短的序列的長度。測試
一段測試代碼以下:編碼
# coding:utf-8 def main(): a = '1234' b = [4,6,7] print zip() # 輸出:[] print zip(a) # 輸出:[('1',), ('2',), ('3',), ('4',)] print zip(a,a) # 輸出:[('1', '1'), ('2', '2'), ('3', '3'), ('4', '4')] print zip(a,[]) # 輸出:[] print zip(a,b) # 輸出:[('1', 4), ('2', 6), ('3', 7)] if __name__ == '__main__': main()
map函數是一個高階函數,支持傳入一個函數做爲參數。先來看它的文檔是怎麼說的:命令行
Docstring: 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).
從map函數的文檔中能夠看出,該函數的第一個參數爲一個函數對象,後面能夠跟一個或多個序列,函數的返回值是一個list.code
對比zip函數的用法,能夠發現其實map函數就是一個加強版的zip函數,與zip函數不一樣的是,map函數支持傳入一個函數參數來處理序列。對象
若是第一個函數參數不爲None,那麼返回的結果list的第i個元素,是將該函數做用於每一個序列的第i個元素的結果。若是傳入的序列的長度不都是相同的,那麼結果list的某些元素將會是None.排序
若是第一個函數參數爲None,那麼返回的的結果list的第i個元素,是每一個序列第i個元素組成的n元組(n爲序列的個數),若是每一個序列的長度不都是相同的,那麼結果list的某些元素將是None.ip
下面經過一段程序來看map函數的實際用法:
# coding:utf-8 def main(): a = [1,2,3,4] b = [3,5,9] c = [8,2,3] print map(None,a,b,c) # 輸出:[(1, 3, 8), (2, 5, 2), (3, 9, 3), (4, None, None)] print map(lambda x : x ** 2,a) # 輸出:[1, 4, 9, 16] # print map(lambda x,y : x + y,a) # 輸出:TypeError <lambda>() takes exactly 2 arguments (1 given) print map(lambda x,y : x + y,b,c) # 輸出:[11, 7, 12] # print map(lambda x,y,z : x + y + z,a,b,c) # 輸出:TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' print map(lambda x,y : x + y if x is not None and y is not None else None,a,b) # 輸出:[4, 7, 12, None] if __name__ == '__main__': main()
先看函數文檔:
Docstring: 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函數接收三個參數:function,seq,init,其中前兩個是必選參數,最後一個爲可選參數。
reduce函數作了這樣一件事情:從左到右遍歷seq,將seq[0]和seq[1]傳入函數function進行運算(function爲一個接收兩個參數的函數),獲得一個結果值,而後將這個結果值再和seq[2]傳入fucntion進行運算再獲得一個新的結果值...以此類推。最終獲得一個值,就是該函數的返回值。
若是傳入了init,那麼init和seq[0]會做爲第一次傳入funciton的參數,若是seq爲空,init也會做爲reduce的返回值返回。
用法示例以下:
# coding:utf-8 def main(): lst = [1,2,3] f = lambda x,y:x*y print reduce(f,lst) # 輸出:6 print reduce(f,lst,-1) # 輸出:-6 print reduce(f,[],-2) # 輸出:-2 if __name__ == '__main__': main()
# coding:utf-8 # 測試base64編解碼 import base64 def main(): s = '123abc' # 編碼 print base64.b64encode(s) # 輸出:MTIzYWJj # 解碼 print base64.b64decode('MTIzYWJj') # 輸出:123abc if __name__ == '__main__': main()