[Python] itertools

2021. 1. 1. 00:56분석 Python/구현 및 자료

728x90

Chain

  • list들을 연결해줄 때 쓸 수 있다.
  • list를 더할 때 + 와 같은 역할을 해준다.
import itertools

letters = ['a', 'b', 'c', 'd', 'e', 'f']
booleans = [1, 0, 1, 0, 0, 1]
decimals = [0.1, 0.7, 0.4, 0.4, 0.5]
print(list(itertools.chain(letters, booleans, decimals)))
print(letters + booleans + decimals)

# ['a', 'b', 'c', 'd', 'e', 'f', 1, 0, 1, 0, 0, 1, 0.1, 0.7, 0.4, 0.4, 0.5]
# ['a', 'b', 'c', 'd', 'e', 'f', 1, 0, 1, 0, 0, 1, 0.1, 0.7, 0.4, 0.4, 0.5]
letters = [['a', 'b'], ['c', 'd', 'e', 'f']]
booleans = [1, 0, 1,[ 0, 0, 1]]
decimals = [[0.1, 0.7], 0.4, 0.4, 0.5]
print(list(itertools.chain(letters, booleans, decimals)))
print(letters + booleans + decimals)

# [['a', 'b'], ['c', 'd', 'e', 'f'], 1, 0, 1, [0, 0, 1], [0.1, 0.7], 0.4, 0.4, 0.5]
# [['a', 'b'], ['c', 'd', 'e', 'f'], 1, 0, 1, [0, 0, 1], [0.1, 0.7], 0.4, 0.4, 0.5]

Count

  • count는 반복하고자 하는 최대수를 미리 알지 않아도 되는 경우이다.
  • 1에서 시작해서 10개씩 건너 띄면서 생성한다
from itertools import count 
for number, letter in zip(count(1, 10), ['a', 'b', 'c', 'd', 'e']):
    print('{0}: {1}'.format(number, letter))
    
1: a
11: b
21: c
31: d
41: e

islice

  • 개인적으로 유용하다고 생각했던 것
  • 전체를 하는 것이 아니라 먼가 일부를 쓰고 싶을 때
  • islice( 전체 범위 , 처음 시작 , 끝 , step)
from itertools import islice
for i in islice(range(1000), 0, 200, 10):
    print(i)

0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190

cycle

  • 유용할 것 같다고 생각이 듦. 홀수, 짝수 3의 배수, 등등으로 먼가 규칙이 있을 때 유용할 것 같다.
from itertools import cycle 
for number, letter in zip(cycle(range(3)), ['a', 'b', 'c', 'd', 'e']):
    print('{0}: {1}'.format(number, letter))
    
0: a
1: b
2: c
0: d
1: e

groupby

  • tuple이 중복되는 이름끼리 모아줄 때 유용할 것 같다
from operator import itemgetter
from itertools import groupby

attempts = [
    ('dan', 87),
    ('erik', 95),
    ('jason', 79),
    ('erik', 97),
    ('dan', 100)
]

# Sort the list by name for groupby
attempts.sort(key=itemgetter(0))
print(attempts)
# Create a dictionary such that name: scores_list
print({key: sorted(map(itemgetter(1), value)) for key, value in groupby(attempts, key=itemgetter(0))})

# [('dan', 87), ('dan', 100), ('erik', 95), ('erik', 97), ('jason', 79)]
# {'dan': [87, 100], 'erik': [95, 97], 'jason': [79]}

defaultdict

  • 사전처럼 바로바로 넣어주기
from collections import defaultdict

counts = defaultdict(list)
attempts = [('dan', 87), ('erik', 95), ('jason', 79), ('erik', 97), ('dan', 100)]

for (name, score) in attempts:
    counts[name].append(score)
print(counts)
# {'dan': [87, 100], 'erik': [95, 97], 'jason': [79]})

repeat

  • 중복된 것 쉽게 여러 개 만들기
from itertools import repeat
print(list(repeat('Hello, world!', 3)))

# ['Hello, world!', 'Hello, world!', 'Hello, world!']

 

dropwhile

  • 10보다 큰 것이 나올 때까지 다 버리고, 나오는 순간부터는 보존
  • 유용할 것 같다.
    • 문자열에서도 적용이 가능하니, 중복되는 것 나오기 전까지는 제거 가능할 것 같다.
from itertools import dropwhile
print(list(dropwhile(lambda x: x < 10, [1, 4, 6, 7, 11, 34, 66, 100, 1])))
print(list(dropwhile(lambda x: x != "ㅁ" , ["ㅋ","ㅠ","ㅇ","ㄴ","ㅁ","1","ㅇ","ㅁ","ㅁ"])))

[11, 34, 66, 100, 1]

['ㅁ', '1', 'ㅇ', 'ㅁ', 'ㅁ']

 

takewhile

  • dropwhile 과는 반대로 10보다 큰 것이 나올 때까지만 남겨 놓기

 

        
from itertools import takewhile
print(list(takewhile(lambda x: x < 10, [1, 4, 6, 7, 11, 34, 66, 100, 1])))
print(list(takewhile(lambda x: x != "는", ["아버지", "는", "가방을", "사셨다."])))

[1, 4, 6, 7]
['아버지']

filter

  • ifilter는 python3에 없습니다
list(filter(lambda x : x < 10 , [1, 4, 6, 7, 11, 34, 66, 100, 1] ))

## [1, 4, 6, 7, 1]

 

까먹는 함수들이니, 잘 적어 놓고 나중에 재사용해야겠다.

728x90