函数式编程:filter的使用方法

按照惯例,在学习filter函数之前在交互模式下看下filter的文档(养成好习惯,不能做拿来主义,自己还是要实验一下的)

python2 >>>

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.

return list tuple string ?if sequence is a tuple or string return the same type else return a list?  

print(type(filter(lambda x: x.islower(),'AbcDEFg')))
>>>>> # <type 'str'>


set(['1', '3', '2', '5', '4', '6'])
print(type(filter(lambda x: int(x) % 2 ==0,l)))
>>>>> # <type 'list'>
>>>>> # else return list


print(type(filter(lambda x: x.islower(),('A','B','C','d','e','f'))))
>>>> # <type 'tuple'>


print(type(filter(lambda x: x.islower(),['A','B','C','d','e','f'])))
>>>> # <type 'list'>

果然,文档肯定没有错!

If funtion is None, return the items that are true (what's true?  )

print(filter(None,[0,1,2,3,4,5,None]))
[1, 2, 3, 4, 5]  

直接判断item是真假了,不再有条件进行判断。

 

python3 >>>

Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.

1. return filter object (iterator)返回一个迭代器对象

 

 

实例:

#!/usr/bin/env python2.7
# -*- coding=utf-8 -*-
def prime(x):
    if x < 1:
        return False
    else:
        for i in range(2,x):
            if x%i == 0:
                return True
        else:
            return False
            
print(filter(prime, range(1,100)))


#!/usr/bin/env python3
# -*- coding=utf-8 -*-
def prime(x):
    if x < 1:
        return False
    else:
        for i in range(2,x):
            if x%i == 0:
                return True
        else:
            return False
            
print(list(filter(prime, range(1,100))))


# python2和python3的区别(基本上就只在于返回的值的不同)

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值