python filter函数中写none_Python内置函数之filter

一: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)

执行结果如下图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值