Skip to content

Instantly share code, notes, and snippets.

@makerj
Created February 9, 2016 12:29
Show Gist options
  • Save makerj/659c330d1f5bff80e88f to your computer and use it in GitHub Desktop.
Save makerj/659c330d1f5bff80e88f to your computer and use it in GitHub Desktop.
#Python itertools

#Python itertools 공식문서를 참조했다.

itertools는 반복 행위가 필요한 부분을 빠르고, 효율적으로 구현할 수 있도록 한다. operator 모듈과도 궁합이 좋다.

##Cheat Sheet


공식 문서에 올라가 있는 것을 전부 나열하는 것은 의미가 없으니 , 예시로 필요한 것만 빼서 정리.

cycle([1,2,3])  # 1 2 3 1 2 3 1 2 3 ...
repeat(10, 3)  # 10 10 10 ...
chain('ABC', 'DEF')  # A B C D E F
compress('ABCDEF', [1,0,1,0,1,1])  # A C E F
zip_longest('ABCD', 'xy', fillvalue='-')  # Ax By C- D-
tee([1,2,3])  # [1,2,3], [1,2,3]
groupby()
[k for k, g in groupby('AAAABBBCCDAABBB')]  # A B C D A B
[list(g) for k, g in groupby('AAAABBBCCD')]  # AAAA BBB CC D

product('ABCD', repeat=2)  # AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations('ABCD', 2)  # AB AC AD BA BC BD CA CB CD DA DB DC
combinations('ABCD', 2)  # AB AC AD BC BD CD

groupby()는 SQL의 GROUPBY절과는 약간 다름에 주의하자. groupby()의 입력으로 들어가는 리스트는 미리 정렬되어 있어야 한다.

더 자세한 내용은 생략한다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment