[TIL] 241123 | python | map | lambda | filter

·2024년 11월 23일

TIL

목록 보기
9/88
  1. 파이썬 문법 뽀개기 16-18

map, lambda, filter 예제

people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7}
    ]
    
def check_adult(person):
    return '성인' if person['age'] > 20 else '청소년'

result1 = map(check_adult, people)
result2 = map(lambda person: ('성인' if person['age'] > 20 else '청소년'), people)
result3 = filter(lambda x: x['age'] > 20, people)

print(list(result1))
print(list(result2))
print(list(result3))
  • 결과
['청소년', '성인', '청소년']
['청소년', '성인', '청소년']
[{'name': 'carry', 'age': 38}]
  • result1: people을 순회하면서 하나하나 check_adult 함수에 넣어라. 그 값을 list로 출력.
  • result2: people을 돌면서 person에 넣고, person을 ('성인' ...)으로 리턴해라. list로 출력.
  • result3: people을 돌면서 person에 넣고 조건에 부합하는 것만 반환. list로 출력.
    • lambda는 주로 x와 함께 사용.

map

  • map(function, iterable)
    • function: 각 요소에 적용할 함수
    • iterable: 함수를 적용하라 데이터 집합. 순환 가능.
  • iterable한 각 요소에 대해 function 함수를 적용한 결과를 새로운 iterator로 반환.
def square(x):
    return x ** 2

abc = [1, 2, 3, 4, 5]

result = map(square, abc)
print(list(result))

# 출력 결과: [1, 4, 9, 16, 25]

lambda

  • lambda 인자 : 표현식
  • def 키워드를 사용하는 것보다 간결하고 간편하게 함수 정의 가능
def add(x, y):
	return x + y
    
add = lambda x, y: x + y

map 함수와 함께 사용하기

llist = [1, 2, 3, 4, 5]

result = list(map(lambda x: x ** 2, llist))
print(result)

filter

  • filter(function, iterable)
    • function: 각 요소의 조건을 정하는 함수
    • iterable: 순회 가능한 자료형
  • function의 조건에 맞는 자료들만 반환.
def smaller_ten(x):
    return x < 10

llist = [1, 5, 10, 15, 20]

filtered = list(filter(smaller_ten, llist))

print(filtered)

# 결과: [1, 5]

lambda 함수와 함께 사용하기

llist = [1, 5, 10, 15, 20]

filtered2 = list(filter(lambda x: x < 10, llist))

print(filtered2)

# 결과: [1, 5]
  • 주의할 점: filter 함수의 반환값 데이터 타입은 'filter'. list나 tuple로 자료형 바꿔줘야 함.

개수 제한 없이 매개변수 입력 받기

  • 인풋 인자들을 무제한으로 받을 수 있다.
  • 파라미터 앞에 '*'을 붙여준다.
def cal(*args):
    for name in args:
        print(f'{name} 밥 먹어라~')
        
result = cal('영수', '철수', '짱구')
print(result)

# 결과: 
영수 밥 먹어라~
철수 밥 먹어라~
짱구 밥 먹어라~

키워드 인수를 여러 개 받기

  • (키워드 = 특정 값) 형태로 함수를 호출할 수 있다.
  • 딕셔너리 형태로 {'키워드':'특정 값'} 형태로 함수 내부에 전달
  • 파라미터 앞에 '**'를 붙여준다.
  • kwargs = key word arguments
def person(**kwargs):
    print(kwargs)

person(name = 'bob', age = 30, height = 180)

# 결과: {'name': 'bob', 'age': 30, 'height': 180}
def kor_name(**kwargs):
    for k, v in kwargs.items():
        print(f'{k} is {v}.')

kor_name(name = '짱구')

# 결과: name is 짱구.
profile
To Dare is To Do

0개의 댓글