filter() 실전예제 20개기초 필터링부터 문자열, 숫자, 딕셔너리, 사용자 정의 함수, map과의 조합까지 단계적으로 익히는 실습 자료
filter(함수, 반복가능객체) 는
함수의 결과가 True인 요소만 골라내는 도구입니다.
nums = [1, 2, 3, 4, 5, 6]
result = list(filter(lambda x: x % 2 == 0, nums))
print(result)
리스트에서 짝수만 남기는 가장 기본적인 filter 예제입니다.
[2, 4, 6]
nums = [1, 2, 3, 4, 5, 6]
result = list(filter(lambda x: x % 2 == 1, nums))
print(result)
조건식이 참인 값만 통과하므로 홀수만 추출할 수도 있습니다.
[1, 3, 5]
nums = [3, 12, 7, 25, 1, 18]
result = list(filter(lambda x: x > 10, nums))
print(result)
크기 비교 조건을 이용하여 원하는 범위의 값만 남길 수 있습니다.
[12, 25, 18]
nums = [-5, 3, -2, 8, -1, 0]
result = list(filter(lambda x: x < 0, nums))
print(result)
0보다 작은 값만 걸러내어 음수 목록을 만듭니다.
[-5, -2, -1]
words = ['hi', 'cat', 'a', 'python', 'go']
result = list(filter(lambda x: len(x) >= 3, words))
print(result)
문자열 길이를 기준으로 필요한 단어만 선택할 수 있습니다.
['cat', 'python']
words = ['apple', '', 'banana', '', 'grape']
result = list(filter(None, words))
print(result)
filter(None, iterable)은 참으로 평가되는 값만 남깁니다. 빈 문자열은 제거됩니다.
['apple', 'banana', 'grape']
nums = [0, 1, 2, 0, 3, 0, 4]
result = list(filter(None, nums))
print(result)
숫자 0은 거짓(False)으로 평가되므로 자동으로 제거됩니다.
[1, 2, 3, 4]
data = [10, None, 20, None, 30]
result = list(filter(lambda x: x is not None, data))
print(result)
None 여부를 직접 검사해서 유효한 데이터만 남기는 예제입니다.
[10, 20, 30]
words = ['Apple', 'banana', 'Cherry', 'dog']
result = list(filter(lambda x: x[0].isupper(), words))
print(result)
문자열의 첫 글자를 검사하여 조건에 맞는 단어만 걸러냅니다.
['Apple', 'Cherry']
words = ['apple', 'banana', 'orange', 'grape', 'egg']
result = list(filter(lambda x: x[0].lower() in 'aeiou', words))
print(result)
문자 포함 여부를 조건으로 활용한 예제입니다.
['apple', 'orange', 'egg']
nums = list(range(1, 21))
result = list(filter(lambda x: x % 3 == 0, nums))
print(result)
range와 함께 사용하면 규칙에 맞는 수만 쉽게 고를 수 있습니다.
[3, 6, 9, 12, 15, 18]
scores = [45, 82, 67, 90, 39]
result = list(filter(lambda x: x >= 60, scores))
print(result)
점수 리스트에서 기준 점수 이상인 값만 남기는 전형적인 활용입니다.
[82, 67, 90]
people = [
{'name': '민수', 'age': 17},
{'name': '지우', 'age': 22},
{'name': '서연', 'age': 19}
]
result = list(filter(lambda x: x['age'] >= 19, people))
print(result)
딕셔너리 안의 특정 키 값을 기준으로 객체를 걸러낼 수 있습니다.
[{'name': '지우', 'age': 22}, {'name': '서연', 'age': 19}]
files = ['main.py', 'note.txt', 'app.py', 'image.png']
result = list(filter(lambda x: x.endswith('.py'), files))
print(result)
문자열 메서드와 결합하면 실무형 필터링이 가능합니다.
['main.py', 'app.py']
texts = ['apple', ' ', 'banana', '', ' grape ']
result = list(filter(lambda x: x.strip() != '', texts))
print(result)
strip()을 활용해 공백만 있는 문자열도 걸러낼 수 있습니다.
['apple', 'banana', ' grape ']
words = ['star', 'sun', 'sky', 'stone', 'moon']
result = list(filter(lambda x: 's' in x, words))
print(result)
문자 포함 여부를 이용해 필요한 단어만 추려냅니다.
['star', 'sun', 'sky', 'stone']
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
nums = list(range(1, 21))
result = list(filter(is_prime, nums))
print(result)
filter에는 lambda뿐 아니라 일반 함수도 넣을 수 있습니다.
[2, 3, 5, 7, 11, 13, 17, 19]
nums = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, nums)
for x in result:
print(x, end=' ')
filter는 iterator를 반환하므로 list로 바꾸지 않고 바로 순회할 수도 있습니다.
2 4 6
nums = [1, 2, 3, 4, 5, 6]
result = list(map(lambda x: x * 10, filter(lambda x: x % 2 == 0, nums)))
print(result)
먼저 filter로 짝수만 고른 뒤 map으로 값을 변환하는 조합 예제입니다.
[20, 40, 60]
nums = [1, 2, 3, 4, 5, 6]
a = list(filter(lambda x: x % 2 == 0, nums))
b = [x for x in nums if x % 2 == 0]
print(a)
print(b)
filter와 리스트 컴프리헨션은 비슷한 결과를 만들 수 있습니다.
[2, 4, 6] [2, 4, 6]