Python

Python 파이썬 map, filter, lambda

5kiran 2022. 11. 21.
반응형

map

people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]

def check_adult(person):
    if person['age'] > 20:
        return '성인'
    else:
        return '청소년'

result = map(check_adult, people)
print(list(result))

 

결과 = ['청소년', '성인', '청소년', '청소년', '성인', '성인', '성인', '성인']

 

map(check_adult, people)

people를 한번씩 도는데 check_adult 함수에 넣어줘라

 

 

짧게 쓴다면

def check_adult(person):
    return '성인' if person['age'] > 20 else '청소년'

result = map(check_adult, people)
print(list(result))

이렇게 사용도 가능하다

 

여기서

lambda

위의 함수를 없애고 lambda로 만든 예시

result = map(lambda x: ('성인' if x['age'] > 20 else '청소년'), people)
print(list(result))

너희 함수 한줄짜리인데 왜 그렇게 길게 만들어?

라는 느낌으로 쓰는 것

 

filter

result = filter(lambda x: x['age'] > 20, people)
print(list(result))
    • map과 아주 유사한데, True인 것들만 뽑기! (map보다 훨씬 쉬워요!)
반응형

'Python' 카테고리의 다른 글

로그인 기능 세션  (0) 2022.12.06
Python 파이썬 조건문과 반복문  (0) 2022.11.21
Python f-string 과 예외처리  (1) 2022.11.21
Python 리스트와 딕셔너리  (0) 2022.11.21
Python 문자열 자르기  (0) 2022.11.21

댓글