reduce

iterable한 객체의 각 요소를 누적적으로 연산한 결과를 반환하는 함수

from functools import reduce
 
reduce(function, iterable, init)
  • function : 각 요소에 적용할 함수 iterable : 함수를 적용할 데이터 집합 init : 초기값 (생략 가능)

📖사용 예시

📎리스트의 각 요소를 역으로 합치기

from functools import reduce
def add(x, y):
    return y + x
 
abcs = ["a", "b", "c", "d", "e"]
 
result = reduce(add, abcs) # edcba
  • 연산 과정 : ((((“e”+“d”)+“c”)+“b”)+“a”)

reduce 함수를 사용하지 않는다면?

def add(x, y):
   return y + x
 
abcs = ["a", "b", "c", "d", "e"]
 
result = ""
for a in abcs:
    result = add(result, a)

📎with lambda

reduce함수로 iterable한 객체의 각 요소를 누적적으로 연산한 결과를 반환할 때, lambda함수로 조건 지정

from functools import reduce
abcs = ["a", "b", "c", "d", "e"]
 
result = reduce(lambda x, y: y + x, abcs) # edcba

📎최솟값/최댓값 구하기

from functools import reduce
maxi = reduce(lambda x, y: x if x>y else y, [1, 2, 3, 4]) # 4
 
mini = reduce(lambda x, y: x if x<y else y, [1, 2, 3, 4]) # 1