python内置函数之filter()
先看官方解释
"""
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.
"""
它的用法有两点:
- function做为过滤条件,过滤出iterable中满足条件的元素,以迭代器的形式返回
- 如果function为None,则返回iterable为true的元素,以迭代器的形式返回
注意:python2返回的结果存放在列表中,python3返回迭代器对象
用法举例1
# 过滤出列表中大于0的元素
g = filter(lambda x: x > 0, [1, 0, 3, -3, 12])
for i in g:
print(i, end=',')
# output: 1,3,12,
用法举例2
# 过滤出列表中的奇数
g = filter(lambda x: x %2 == 1, [1, 0, 3, -3, 12])
for i in g:
print(i, end=',')
# output: 1,3,-3,
用法举例3
# 过滤出不为假的元素
g = filter(None, ['abc', 0, False, 'abcde', 'abcdefg'])
for i in g:
print(i, end=',')
# output: abc,abcde,abcdefg,
g = filter(None, [])
for i in g:
print(i, end=',')
# output: 返回空