按照惯例,在学习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的区别(基本上就只在于返回的值的不同)