개발일기 [Python 파이썬]

[Python map, filter, lambda] 파이썬 맵, 람다, 필터

neullo 2024. 2. 20. 11:27

map - 리스트의 모든 원소를 조작할 수 있는 맵, 필터, 람다를 배워보자

다양한 사람들의 이름과 나이가 들어있는 {dictionary} 사전을 [리스트]로 나열해 놓은 정보가 사람 정보가 있다고 가정하자.

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} ]

 

1차 Python Map :

result = map(check_adult, people)

check_adult라고 함수를 주고 조건으로 Check_adult 만약 20살이 넘으면 성인을 보여주고, 아니면 청소년이라고 알려줘라고 부탁해 보자.

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

result = map(check_adult, people) 

print(list(result)) #여기서 그냥 print(result)만 해주면 result=map 이기때문에 list로 감싸기

 

**여기서 print(result)만 해주면 result=map 이기 때문에 list로 프린트할 결괏값을 한번 감싸기 

이걸 run 하면 위에 다양한 사람들 이름과 나이를 check_adult 해서 '청소년', '성인', '청소년'과 같이 리스트로 알려준다.

 


2차 Python Lamda :

result = map(lamda x: x, people)

이걸 조금 더 간단히 쓸 수도 있다. 맵(map)옆 괄호에 ( ) 람다(lamda)를 넣어주자.

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

-  result = map(check_adult, people)

result = map(lamda x: x, people)

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

 

*** x:x의 자리는 person:person이 들어가는 것과 같다. x는 람다에서 관용적으로 많이 쓰인다.

그러면 이때 person: 내가 원하는정보 이렇게 출력되기를 원하니 두번째 x 자리에 먼저 만들어 놓았던 짧은 if문을 그대로 넣어 주자. 

result = map(lamda person: ('성인' if person['age'] > 20 else '청소년'), people)

 

 

***여기서 간단히 쓸 수 있는 if 함수는 이 글을 참고하자

[Python] 파이썬 긴 코드 짧게 만들어주는 함수 def , [파이썬] return과 print의 차이점 

 

[Python] 파이썬 긴 코드 짧게 만들어주는 함수 def , [파이썬] return 과 print의 차이점

파이썬 def 함수 문법, 언제 쓰는 걸까? def는 함수를 만들 때 사용하는 예약어이며, 함수 이름은 함수를 만드는 사람이 임의로 만들 수 있다. 함수 이름 뒤 괄호 안의 매개변수는 이 함수에 입력으

neulo.tistory.com

[Python] 파이썬 조건문 (if), 반복문 (for) 

 

Python 조건문 (if), 반복문 (for)

IF & ELSE 내가 5000원이 있는데, 만약 3000원 이상이면 '택시를 탈게' 아니면 '택시를 못타' 라는 두 개의 조건문 `money = 5000` `if money > 3000:` `print('take taxi')` `else:` `print('cannot take taxi')` IF & ELIF & ELSE 내

neulo.tistory.com

 


 

3차 Python Filter:  

print(list(result)) and filter

filter는 map과 아주 유사한데, True인 것들만 뽑는다. 사람의 나이가 [age] > 20 살 보다 큰 친구들만 뽑아보자 .

 

result = filter(lambda x: x['age'] > 20, people) 
print(list(result))

 

먼저 map을 filter로 바꾸어주자. 

-  result = map(check_adult, people)

-  result = filter(check_adult, people)

 result = filter(lamda x: x, people)

 result = map(lamda person: person, people)

 result = map(lamda person: person[age]>20, people)

 

***x:x의 자리는 person:person이 들어가는 것과 같다고 했다.