Jihun Oh

itertools 본문

Engineering/Python

itertools

Jihun Oh 2025. 4. 5. 15:22

무제한 이터레이터

from itertools import count, cycle, repeat, accumulate, pairwise

count(start=10, step=2) # 10 12 14 16 18 ...
cycle('ABCD') # A B C D A B C D ...
repeat(10, 3) # 10 10 10
accumulate([1, 2, 3, 4, 5]) # 1 3 6 10 16
pairwise('ABCDEFG') # AB BC CD DE EF FG

 

조합형 이터레이터

from itertools import combinations, combinations_with_replacement, permutations

l = [1,2,3]
for i in combinations(l, 2):
	print(i)
    
# output
(1, 2)
(1, 3)
(2, 3)

for i in combinations_with_replacement(l, 2):
	print(i)
    
# output
(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)

for i in permutations(l):
	print(i)
    
# output
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)


l1 = ['A', 'B']
l2 = ['1', '2']

for i in product(l1, l2, repeat=1):
	print(i)
    
# output
('A', '1')
('A', '2')
('B', '1')
('B', '2')

'Engineering > Python' 카테고리의 다른 글

Python 코드 정적 분석 도구  (0) 2025.06.15
re  (0) 2025.04.05
collections (defaultdict, Counter, OrderedDict, deque, namedtuple)  (0) 2024.05.15
generator  (0) 2024.04.14
set, tuple  (0) 2024.04.14