2. map, filter, reduce for list

참고 블로그 : https://3months.tistory.com/338?category=753896
참고 사이트 : Intermediate python (http://book.pythontips.com/en/latest/)

MAP

  • map(lambda x: 새로운작업 , list)형태로 iterator를 반환하므로 lambda함수로 기존리스트를 수정한 리스트를
    next()로 하나씩 뽑아내거나, list()로 감싸서 한번에 가져올 수 있다.

map 없이새로운 리스트 반환하기

In [2]:
items = [1, 2, 3, 4, 5]
squared = []

for i in items:
    squared.append(i ** 2)

squared
Out[2]:
[1, 4, 9, 16, 25]

map을 사용하여 수정된 리스트를 한번에 반환

In [5]:
items = [1, 2, 3, 4, 5]
(lambda x : x**2, items)
Out[5]:
(<function __main__.<lambda>(x)>, [1, 2, 3, 4, 5])
In [20]:
square_map = map(lambda x : x**2, items)
square_map
Out[20]:
<map at 0x2e668f65f28>
In [37]:
next(map(lambda x : x**2, items))
Out[37]:
1
In [38]:
list(square_map)
Out[38]:
[1, 4, 9, 16, 25]
In [ ]:
 

Filter

  • filter(lambda x : x조건 , list ) 의 형태로 해당 list에서 조건을 만족시키는 요소만 뽑아올 수 있다. 마지막에는 list() 로 감싸줘야 리스트로 가져온다.
  • comprehension 시 if문을 넣는것과 동일 하다
In [39]:
list_ = range(-5, 5)
list_
Out[39]:
range(-5, 5)
In [42]:
filter( lambda x : x <0, list_)
Out[42]:
<filter at 0x2e668f7a4e0>
In [43]:
list( filter( lambda x : x <0, list_) )
Out[43]:
[-5, -4, -3, -2, -1]
In [45]:
## comprehenshion으로 구현
[ x for x in list_ if x<0 ]
Out[45]:
[-5, -4, -3, -2, -1]
In [ ]:
 

Reduce

  • reduce(lambda x, y : x + y, 순서형 자료-**(리스트, 튜플, 문자열)**)의 형태로 순서대로 x와 y에 차면서, 그결과는 x에 누적되고 새로운 순서의 요소는 y에 들어와서 계산.

1부터 100까지 for문으로 합 구하기

In [47]:
sum_ = 0
for i in range(1, 101):
    sum_ += i
    
sum_
Out[47]:
5050

1부터 100까지 reduce로 구하기

In [49]:
from functools import reduce

# (1) + (2) -> 3+ (3)  -> 6+ (4)
reduce(lambda x, y : x+y, range(1, 101))
Out[49]:
5050
In [50]:
# 다른 예제 - 순서형자료에 list대신 문자열
reduce(lambda x, y : y + x, 'abc')
Out[50]:
'cba'

numpy로 쉽게 구하기

  • 리스트들의 합을 np.sum()으로 구하기 마치 칼럼의 합을 쉽게 구하듯이
In [52]:
import numpy as np

np.sum( [x for x in range(1, 101)] )
Out[52]:
5050
In [ ]:
 

+ Recent posts