作用
filter()方法通过测试序列中每个元素是否为真的函数来过滤给定的序列。
语法
filter(function, sequence)
Example 1: 过滤list 值
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)
Example 2: 结合lambda 表达式
seq = [0, 1, 2, 3, 5, 8, 13]
result = filter(lambda x: x % 2 != 0, seq)
result = filter(lambda x: x % 2 == 0, seq)
参考: