標籤:function sequence filter return 布爾 python
一: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.
說明:
filter(func,seq)
調用一個布爾函數func來迭代遍曆每個seq中的元素;返回一個使func傳回值為True的元素的序列
例子:
>>> list1=[1,2,3] --定義一個列表>>> filter(None,list1) --如果function 為 None ,那麼返回序列全部[1, 2, 3]>>> >>> list2=[1,2,3,4]>>> def f1(x): --對於序列X中的每個item依次進行判斷,如果滿足某個條件就返回真,不滿足就返回假... if x>2:... return True... else:... return False... >>> filter(f1,list2) --返回在函數f1中滿足條件的item,如果序列是元祖,那麼返回的結果也是元祖,字串和列表同理[3, 4]>>>
實際的案例
比如要求輸出/etc/passwd密碼檔案中所有以/bin/bash 結尾的使用者到一個列表中
程式編寫思考:可以利用readlines函數將/etc/passwd檔案輸出到一個列表中,然後寫一個布爾函數判斷如果列表中的子串是以/bin/bash結尾的那麼就返回真,如果不是那麼就返回假,再利用filter函數進行過濾,即可達到要求
PYTHON代碼如下
#!/usr/bin/env python# coding:utf-8# @Filename: checkpwd.pt def show_file(file): ‘‘‘Open file and returns the file content‘‘‘ fp = open(file) contentList = fp.readlines() fp.close() return contentList def filter_line(listArg): ‘‘‘Filter out the lines that end in /bin/bash in the /etc/passwd‘‘‘ if listArg.strip(‘\n‘).endswith(‘/bin/bash‘): return True else: return False def show_user(filterArg): ‘‘‘Append the user to list‘‘‘ showList=[] for i in filterArg: showList.append(i[:i.index(‘:‘)]) print showList if __name__ == ‘__main__‘: file = ‘/etc/passwd‘ clist = show_file(file) flist = filter(filter_line,clist) show_user(flist)
執行結果如
650) this.width=650;" src="http://s4.51cto.com/wyfs02/M00/8A/BF/wKiom1g6aY3TWPkvAAAZHU2mIbI493.png-wh_500x0-wm_3-wmp_4-s_588297671.png" title="23acefb9-e283-47d1-a2d8-186c6ba63873.png" alt="wKiom1g6aY3TWPkvAAAZHU2mIbI493.png-wh_50" />
本文出自 “明鏡亦非台” 部落格,請務必保留此出處http://kk876435928.blog.51cto.com/3530246/1877014
Python內建函數之filter