[Python] itertools

SuyeonΒ·2021λ…„ 9μ›” 23일
0

Python

λͺ©λ‘ 보기
3/3
post-thumbnail

Functions creating iterators for efficient looping.

Combinatoric iterators

  • ν•˜λ‚˜ μ΄μƒμ˜ λ°°μ—΄μ˜ λͺ¨λ“  쑰합을 κ΅¬ν• κ²½μš°: proudct
  • ν•˜λ‚˜μ˜ λ°°μ—΄μ˜ λͺ¨λ“  쑰합을 ꡬ할 경우: permutation, combination

product

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

permutation

(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

combination

쀑볡을 ν¬ν•¨ν•˜μ§€ μ•ŠμŒ

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')]

accumulate

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]

groupby

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}]

Infinite iterators

count

from itertools import count

for i in count(10):
    print(i)
    if i == 15:
        break
# 10, 11... 15

repeat

from itertools import repeat

for i in repeat(1, 4):
    print(i)
# 1,1,1,1

cycle

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...
profile
Hello World.

0개의 λŒ“κΈ€