파이썬[Python]: itertools - accumulate 함수

파이썬(Phthon): itertools 모듈 - accumulate 함수(function)


/// 설명

기본값으로 누적되어진 값을 반환합니다.(a1, a1+a2=b1, b1+a3=c1, c1+a4 ...)
func 가 인자로 주어진 경우 함수에 주어진 연산을 누적으로 행하며, initial 은 초기값을 설정하는데 사용됩니다.
list = [a1, a2, a3, a4, a5 ...]
(a1, a1 op a2 = b, b op a3 = c, c op a4 = d, d op a5 ...)

※ 형식
itertools.accumulate(iterable[, func, *, initial=None])

reference
https://docs.python.org/3/library/itertools.html#module-itertools

/// 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import itertools
 
test = [14682305]
 
test_ac = list(itertools.accumulate(test))
print(test_ac)  # [1, 5, 11, 19, 21, 24, 24, 29]
 
test_func = lambda x, y: x + y
test_ac = list(itertools.accumulate(test, test_func))
print(test_ac)  # [1, 5, 11, 19, 21, 24, 24, 29]
 
test_ac = list(itertools.accumulate(test, initial=10))
print(test_ac)  # [10, 11, 15, 21, 29, 31, 34, 34, 39]
 
test_ac = list(itertools.accumulate(test, max))
print(test_ac)  # [1, 4, 6, 8, 8, 8, 8, 8]
 
test_func = lambda x, y: x if x >= y else y
test_ac = list(itertools.accumulate(test, test_func))
print(test_ac)  # [1, 4, 6, 8, 8, 8, 8, 8]
 
test_func = lambda _, x: x * 2
test_ac = list(itertools.accumulate(test, test_func))
print(test_ac)  # [1, 8, 12, 16, 4, 6, 0, 10]
 
cs

* 실행환경: Microsoft Windows 10 Homes
* 인터프리터: 파이썬(Python 3.9)


– 당신을 응원합니다. –

댓글

이 블로그의 인기 게시물

파이썬[Python]: 내장함수 - from_bytes 메서드

파이썬[Python]: 내장함수 - __len__ 메서드

파이썬[Python]: kivy - 한글 사용

파이썬[Python]: 내장함수 - bit_length 메서드

C 언어: sin 함수, cos 함수, tan 함수