filter()方法借助一个测试序列中每个元素是否为真的函数来过滤给定的序列。
【python如何使用filter()(用法示例)】语法如下:
filter(function, sequence)
Parameters:
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:
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 ! = 0 , 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函数更多细节。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
推荐阅读
- C++开发环境部署(环境设置详细介绍)
- Python MongoDB如何使用insert_many查询(示例)
- 如何使用JavaScript检查元素是否是父元素的子元素()
- 联想笔记本Ghost win7系统装机版64位最新推荐
- ie9 原版win7 64位系统工具最新推荐
- ASUS win7专业版64激活工具图文详细教程图解
- win764位旗舰版密钥分享制作详细说明
- 原版windows7激活工具最新推荐
- 本文教你安装原版windows7系统镜像文件