본문 바로가기
Python tips

map(), filter(), pipe()를 활용하여 데이터 다루기

by 스티브 십잡스 2024. 4. 8.

map(), filter() 함수는 리스트 안의 데이터를 내가 원하는 대로 추출하거나 변형시킬 수 있습니다.

def square(num):
    return num**2

number_list = [1, 2, 3, 4, 5]
result = map(square, number_list)
print(result) # <map object at ...> 
# for loop -> [1, 4, 9, 16, 25]
print(list(result)) # [1, 4, 9, 16, 25]

# 람다
result = list(map(lambda x: x**2, number_list))
print(result) # [1, 4, 9, 16, 25]
  • map()의 리턴 데이터 타입은 map object
  • filter() 또한 filter object

 

리스트 to 리스트를 통해 DB에서 조회한 데이터를 원하는 형태의 Response class로 변형시킬 수 있습니다.

리스트를 dict 타입으로 변형시키는 방법은 아래와 같습니다.

class Order:
    id: int
    name: str
    quantity: int
    ...
    
    def __init__(self, ...):
        self. ...
        pass

# 람다를 활용하여 주문 상품 : 개수
orders = [Order(1, "과자", 3), Order(2, "아이스크림", 1), Order(3, "물", 5)]
result = dict(map(lambda x: (x.name, x.quantity), orders))
print(result) # {"과자": 3, "아이스크림": 1, "물": 5}
  • 람다식 내부에 (key, value)를 유의
  • 람다식 대신에 callable한 값을 넣을 수도 있다. (일급 함수)

 

from toolz import pipe


numbers = [1, 2, 3, 4, 5]
result = pipe(nums, 
    lambda x: map(lambda y: y**2, x), 
    lambda x: filter(lambda y: y > 15, x), 
    list,
)
print(result)  # [16, 25]
  • pip install toolz
  • map(), filter()를 조합한 데이터 파이프라인을 만들어 볼 수 있습니다.