zoukankan      html  css  js  c++  java
  • Python3 filter()函数

    定义:

    class filter(object):
    """
    filter(function or None, iterable) --> filter object

    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true.
    """

    filter: 过滤,筛选

    返回一个新的迭代器对象,把给入filter的iterable中每个元素作为参数传递给函数function,将function返回为true的元素保留到新迭代器对象。如果函数为None,则全部保留。

    用法:

    filter(function or None, iterable)

    function:函数

    iterable:可迭代对象

    代码举例一:

    def is_positive(n):
        return n > 0
    
    tmplist = filter(is_positive, [-3, -2, -1, 0, 1, 2, 3])
    print(tmplist)
    print(list(tmplist))

    is_positive函数,当输入为正数时,输出True,打印如下

    <filter object at 0x000001BC0B2776D8>
    [1, 2, 3]

    此时输出是:<filter object at 0x0000018857EC76D8>

    可以用list() 转化为列表

    function为None时,不过滤,全部保留

    tmplist = filter(None, [-3, -2, -1, 0, 1, 2, 3])
    print(list(tmplist))

     输出: [-3, -2, -1, 1, 2, 3]

    代码举例二:

    把上述函数写成匿名函数

    tmplist = filter(lambda x: x>0, [-3, -2, -1, 0, 1, 2, 3])
    print(list(tmplist))

    输出:[1, 2, 3]

    注意:

    在python3中,filter返回一个可iterable的对象,但不是一个列表,在Python2中,返回一个列表。

  • 相关阅读:
    Nginx 反向代理接收用户包体方式
    Nginx http反向代理流程Proxy_pass模块
    Nginx 负载均衡一致性算法
    Nginx 负载均衡哈希算法:ip_hash与hash模块
    Nginx upstream模块
    Nginx upstream变量
    Nginx 反向代理与负载均衡基本原则
    19 浏览器缓存
    6 Cookie和Session
    5 Post和Get
  • 原文地址:https://www.cnblogs.com/gaby-yan/p/15067978.html
Copyright © 2011-2022 走看看