一:filterHelp 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)
执行结果如下图