当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python filter()用法及代码示例


filter()方法借助一个测试序列中每个元素是否为真的函数来过滤给定的序列。

用法:

filter(function, sequence)
参数:
function:function that tests if each element of a 
sequence true or not.
sequence:sequence which needs to be filtered, it can 
be sets, lists, tuples, or containers of any iterators.
返回:
returns an iterator that is already filtered.
# function that filters vowels 
def fun(variable):
    letters = ['a', 'e', 'i', 'o', 'u'] 
    if (variable in letters):
        return True
    else:
        return False
  
  
# sequence 
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] 
  
# using filter function 
filtered = filter(fun, sequence) 
  
print('The filtered letters are:') 
for s in filtered:
    print(s)

输出:


The filtered letters are:
e
e

应用:
通常与Lambda函数一起使用以分隔列表,元组或集合。

# a list contains both even and odd numbers.  
seq = [0, 1, 2, 3, 5, 8, 13] 
  
# result contains odd numbers of the list 
result = filter(lambda x:x % 2, seq) 
print(list(result)) 
  
# result contains even numbers of the list 
result = filter(lambda x:x % 2 == 0, seq) 
print(list(result))

输出:

[1, 3, 5, 13]
[0, 2, 8]

请参考Python Lambda函数以获取更多详细信息。



相关用法


注:本文由纯净天空筛选整理自pawan_asipu大神的英文原创作品 filter() in python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。