Python中的filter()函数

目录

一、描述

语法

返回值

二、实例

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

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


一、描述

英文文档

filter(functioniterable)

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable iffunction(item)) if function is not None and (item for item in iterable if item) if function is None.

See  for the complementary function that returns elements of iterable for which functionreturns false.

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

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

语法

filter(function, iterable)

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

返回值

返回一个迭代器对象(不是原有数据类型,需转换格式)


二、实例

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)

输出结果 :[1, 3, 5, 7, 9]

结合前面学到的Lambda表达式,可以使用函数式编程来实现

#!/usr/bin/python3 

tmplist = filter(lambda x:x%2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 
newlist = list(tmplist) 
print(newlist)

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

#!/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)

输出结果 :[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W_chuanqi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值