首页 > 编程语言 > 详细

Python filter() 函数

时间:2020-07-26 19:19:17      阅读:42      评论:0      收藏:0      [点我收藏+]

描述

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。每组词 www.cgewang.com

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

注意: Pyhton2.7 返回列表,Python3.x 返回迭代器对象,具体内容可以查看:Python3 filter() 函数

语法

以下是 filter() 方法的语法:

filter(function, iterable)

参数

  • function -- 判断函数。
  • iterable -- 可迭代对象。

返回值

返回列表。


实例

以下展示了使用 filter 函数的实例:

过滤出列表中的所有奇数:

#!/usr/bin/python # -*- coding: UTF-8 -*- def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(newlist)

输出结果 :

[1, 3, 5, 7, 9]

过滤出1~100中平方根是整数的数:

#!/usr/bin/python # -*- coding: UTF-8 -*- import math def is_sqr(x): return math.sqrt(x) % 1 == 0 newlist = filter(is_sqr, range(1, 101)) print(newlist)

输出结果 :

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Python filter() 函数

原文:https://www.cnblogs.com/yc10086/p/13379876.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!