Functions creating iterators for efficient looping.
proudct
permutation
, combination
cartesian product, equivalent to a nested for-loop. (λ°μΉ΄λ₯΄νΈ κ³±μΌλ‘ λΆλ¦Ό)
from itertools import product
# μμ 1
a = [1, 2]
b = [3, 4]
prod = product(a, b)
print(list(prod)) # [(1, 3), (1, 4), (2, 3), (2, 4)]
# μμ 2
prod = product('ABCD', repeat=2)
print(list(prod)) # AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
(1,2), (2,1)κ³Ό κ°μ μ€λ³΅μ ν¬ν¨
from itertools import permutations
# μμ 1
a = [1, 2, 3]
perm = permutations(a, 2)
print(list(perm)) # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
# μμ 2
perm = permutations('ABCD', 2)
print(list(perm)) # AB AC AD BA BC BD CA CB CD DA DB DC
μ€λ³΅μ ν¬ν¨νμ§ μμ
from itertools import combinations
# μμ 1
a= [1,2,3,4]
comb = combinations(a, 3)
print(list(comb))
# [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
# μμ 2
comb = combinations('ABCD', 3)
print(list(perm)) # [('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'C', 'D'), ('B', 'C', 'D')]
from itertools import accumulate
a = [1,2,3,4]
acc1 = accumulate(a)
print(list(acc1)) # [1, 3, 6, 10]
b = [1,3,7,5]
acc2 = accumulate(b, func=max)
print(list(acc2)) # [1, 3, 7, 7]
from itertools import groupby
# μμ 1
a = [1, 2, 3, 4, 5]
group1 = groupby(a, key=lambda x: x < 3)
for key, value in group1:
print(key, list(value))
# True [1, 2]
# False [3, 4, 5]
# μμ 2
persons = [
{'name': 'Hanna', 'age': 54},
{'name': 'Suyeon', 'age': 26},
{'name': 'Sarang', 'age': 20},
{'name': 'Jim', 'age': 20}
]
group2 = groupby(persons, key=lambda x: x['age'])
for key, value in group2:
print(key, list(value))
# 54 [{'name': 'Hanna', 'age': 54}]
# 26 [{'name': 'Suyeon', 'age': 26}]
# 20 [{'name': 'Sarang', 'age': 20}, {'name': 'Jim', 'age': 20}]
from itertools import count
for i in count(10):
print(i)
if i == 15:
break
# 10, 11... 15
from itertools import repeat
for i in repeat(1, 4):
print(i)
# 1,1,1,1
from itertools import cycle
cycle_list = [1, 2, 3]
for i in cycle(cycle_list):
print(i)
if i == 3:
break
# 1,2,3,1,2,3...