菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python filter() 函数

Python 内置函数 Python 内置函数


描述

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

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

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

语法

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

filter(function, iterable)

参数

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

返回值

返回列表。


实例

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

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

#!/usr/bin/python# -*- coding: UTF-8 -*-defis_odd(n): returnn % 2 == 1newlist = 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 -*-importmathdefis_sqr(x): returnmath.sqrt(x) % 1 == 0newlist = filter(is_sqr, range(1, 101))print(newlist)

输出结果 :

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

Python 内置函数 Python 内置函数

AI 思考中...

1 篇笔记 写笔记

  1. #0

    Robin_go

    dou***[email protected]

    538

    关于filter()方法, python3和python2有一点不同

    Python2.x 中返回的是过滤后的列表, 而 Python3 中返回到是一个 filter 类。

    filter 类实现了 __iter__ 和 __next__ 方法, 可以看成是一个迭代器, 有惰性运算的特性, 相对 Python2.x 提升了性能, 可以节约内存。

    a = filter(lambda x: x % 2 == 0, range(10))
    print(a)

    输出

    <filter object at 0x0000022EC66BB128>

    Robin_go

    dou***[email protected]

    9年前 (2017年12月09日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /