Python/Python Programming

[Python] 파이썬 내장함수 - filter

Pydole 2018. 4. 15. 01:00

반복가능(iterable)한 자료에서 특정조건을 만족하는 값만을 편리하게 추출

 

filter(function, iterable)

 


 

 

반복가능한 객체에서 100이하 수만 필터

 

def func1(value): 
    result = []
    
    for num in value:
        if num <= 100:
            result.append(num)

    return result
    

print(func1([97, 98, 99, 100, 101, 102]))
--------------------------------------------
[97, 98, 99, 100]

 

 

 

filter 함수를 이용하여 간단하게 작성

 

def func1(x):
    return x <= 100

print(list(filter(func1,[97, 98, 99, 100, 101, 102])))
------------------------------------------------------
[97, 98, 99, 100]

 

 

 

lambda를 이용하여 한줄로 작성

 

print(list(filter(lambda x: x<=100,[97, 98, 99, 100, 101, 102])))
-----------------------------------------------------------------
[97, 98, 99, 100]