Python
[Python] python 내장 함수 filter
AHHYE
2021. 1. 19. 11:15
조건 함수를 만족하는 데이터만을 추려냄!
* 필터 형태로 반환하므로 리스트나 튜플로 변환해주어야 함
1) 일반 함수 사용
friends = [{'name': 'Robert Downey Jr.', 'role': 'Iron Man', 'nationality': 'the United States'},
{'name': 'Tom Holland', 'role': 'Spider Man', 'nationality': 'the United Kingdom'},
{'name': 'Chris Evans', 'role': 'Captain America', 'nationality': 'the United States'},
{'name': 'Chris Hemsworth', 'role': 'Thor', 'nationality': 'Australia'}]
def IsAmerican(data):
return data["nationality"] == "the United States"
filter(IsAmerican, friends) # <filter object at 0x000001E45BF7A550>
list(filter(IsAmerican, friends))
# [{'name': 'Robert Downey Jr.', 'role': 'Iron Man', 'nationality': 'the United States'},
# {'name': 'Chris Evans', 'role': 'Captain America', 'nationality': 'the United States'}]
2) 람다 함수 사용
friends = [{'name': 'Robert Downey Jr.', 'role': 'Iron Man', 'nationality': 'the United States'},
{'name': 'Tom Holland', 'role': 'Spider Man', 'nationality': 'the United Kingdom'},
{'name': 'Chris Evans', 'role': 'Captain America', 'nationality': 'the United States'},
{'name': 'Chris Hemsworth', 'role': 'Thor', 'nationality': 'Australia'}]
filter(lambda f: f["nationality"] != "the United States", friends) # <filter object at 0x000001E45BF7ADD8>
list(filter(lambda f: f["nationality"] != "the United States", friends))
# [{'name': 'Tom Holland', 'role': 'Spider Man', 'nationality': 'the United Kingdom'},
# {'name': 'Chris Hemsworth', 'role': 'Thor', 'nationality': 'Australia'}]
Falsy Values 제거
* 0, False, None, [], () ..
list1 = [0, 1, 2, 3, False, 0, 4]
list2 = [1, False, 2, 3, None, 'abc']
list3 = [[], (), 'a', 'b', 1, 2]
print(list(filter(bool, list1))) # [1, 2, 3, 4]
print(list(filter(bool, list2))) # [1, 2, 3, 'abc']
print(list(filter(bool, list3))) # ['a', 'b', 1, 2]