zoukankan      html  css  js  c++  java
  • 024_Python3 filter 函数高级用法

    # -*- coding: UTF-8 -*-
    
    '''
    filter(function, iterable)
        function -- 判断函数。
        iterable -- 可迭代对象
    
    功能:
        filter的功能是过滤掉序列中不符合函数条件的元素,当序列中要删减的元素可以用某些函数描述时,就应该想起filter函数。
    返回值
        返回一个迭代器对象
    '''
    import math
    
    
    # 1. 求奇数
    def is_odd(n):
        return n % 2 == 1
    
    
    lst = list(filter(is_odd, [i + j for i in range(1, 3) for j in range(4, 6)]))
    print(lst)  # [5, 7]
    
    
    # 2. 求完全平方数
    def is_sqr(x):
        # 判断是否是整数的方法
        return math.sqrt(x) % 1 == 0
    
    
    lst = list(filter(is_sqr, range(1, 101)))
    print(lst)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    # 3. 与 lambda
    lst = list(filter(lambda x: math.sqrt(x) % 1 == 0, range(1, 101)))
    print(lst)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    # -*- coding: UTF-8 -*-

    '''
    filter(function, iterable)
    function -- 判断函数。
    iterable -- 可迭代对象

    功能:
    filter的功能是过滤掉序列中不符合函数条件的元素,当序列中要删减的元素可以用某些函数描述时,就应该想起filter函数。
    返回值
    返回一个迭代器对象
    '''
    import math


    # 1. 求奇数
    def is_odd(n):
    return n % 2 == 1


    lst = list(filter(is_odd, [i + j for i in range(1, 3) for j in range(4, 6)]))
    print(lst) # [5, 7]


    # 2. 求完全平方数
    def is_sqr(x):
    # 判断是否是整数的方法
    return math.sqrt(x) % 1 == 0


    lst = list(filter(is_sqr, range(1, 101)))
    print(lst) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    # 3. lambda
    lst = list(filter(lambda x: math.sqrt(x) % 1 == 0, range(1, 101)))
    print(lst) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • 相关阅读:
    LeetCode-Cycle Detection,Find the Duplicate Number
    LeetCode-Symmetric Tree
    剑指offer-打印链表倒数第k个结点
    Http协议中Get和Post的区别
    ORDER BY 语句
    AND 和 OR 运算符
    WHERE 子句
    SQL SELECT DISTINCT 语句
    SQL SELECT 语句
    SQL DML 和 DDL
  • 原文地址:https://www.cnblogs.com/luwei0915/p/14612093.html
Copyright © 2011-2022 走看看