小白教程
所有教程
关于
Search
172.69.58.33
172.69.58.33
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Python3 func filter”的源代码
本页内容
上一节:
Python_func_bytearray
下一节:
Python_func_issubclass
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:filter()}}[[Category:python3 built in functions|31]] = Python3 filter() 函数 = [[python3 built in functions|Python3 内置函数]] == 描述 == '''filter()''' 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。 === 语法 === 以下是 filter() 方法的语法: <sample title="" desc="" lang="python" hererun="1"> filter(function, iterable) </sample> === 参数 === * function -- 判断函数。 * iterable -- 可迭代对象。 === 返回值 === 返回一个迭代器对象 以下展示了使用 filter 函数的实例: == 过滤出列表中的所有奇数: == <sample title="" desc="" lang="python" hererun="1"> #!/usr/bin/python3 def is_odd(n): return n % 2 == 1 tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) newlist = list(tmplist) print(newlist) </sample> 输出结果 : <sample title="" desc="" lang="python" hererun="1"> [1, 3, 5, 7, 9] </sample> == 过滤出1~100中平方根是整数的数: == <sample title="" desc="" lang="python" hererun="1"> #!/usr/bin/python3 import math def is_sqr(x): return math.sqrt(x) % 1 == 0 tmplist = filter(is_sqr, range(1, 101)) newlist = list(tmplist) print(newlist) </sample> 输出结果 : <sample title="" desc="" lang="python" hererun="1"> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] </sample> [[python3 built in functions|Python3 内置函数]]
返回至“
Python3 func filter
”。
上一节:
Python_func_bytearray
下一节:
Python_func_issubclass