码迷,mamicode.com
首页 > 编程语言 > 详细

python----高阶函数filter()

时间:2019-06-04 12:42:50      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:false   nbsp   sqrt   port   function   传递   iter   对象   元素   

一、描述
  filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。该接收两个参数,第一个为函数,第二个为序列,序列的每个元素
作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

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

filter(function, iterable)

  参数:function----为判断函数
     iterable----为可迭代对象
  返回值:
      最后返回一个列表

三、实例

def even(num):
    if num%2 == 0:
        return True
    else:
        return False
lis =[1,2,3,4,5,6]
res = filter(even,lis)
print(list(res))#filter只保留返回为真的数据

输出结果:

[2, 4, 6]

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

def is_odd(n):
    return n % 2 == 1

newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(newlist))

输出结果:

[1, 3, 5, 7, 9]

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

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0

newlist = filter(is_sqr, range(1, 101))
print(list(newlist))

输出结果:

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

 

 

 

python----高阶函数filter()

标签:false   nbsp   sqrt   port   function   传递   iter   对象   元素   

原文地址:https://www.cnblogs.com/yttbk/p/10972653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!