티스토리 뷰

Programing language/Python

Python - itertools

내일도이렇게 2019. 10. 5. 18:26

itertools -

   데이터 처리하는 데 유용한 많은 함수와 제네레이터가 포함되어 있는 모듈 

 

 

패키지 임포트

import itertools

 

 

chain() 

    - 리스트( lists/tuples/iterables ) 를 연결하는 것

import itertools

alpa =['a','b','c','d']
number = [1,2,3,4,5,6]
test=('x','y','z')

print(list(itertools.chain(alpa,number,test)))



=========RESULT ===========================

['a', 'b', 'c', 'd', 1, 2, 3, 4, 5, 6, 'x', 'y', 'z']

 

 

dropwhile()  

from itertools import dropwhile

number_list = [2,10,22,44,66]

print(list(dropwhile(lambda x: x < 20 ,number_list)) )



======= Result ======
[22, 44, 66]

20보다 큰것이 나올 때까지 모든 요소는 드랍시키고 나머지것을 리턴함

 

 

takewhile()

from itertools import takewhile

number_list = [2,10,22,44,66]

print(list(takewhile(lambda x: x < 20 ,number_list)) )


======RESULT========
[2, 10]

20보다 큰 것이 나올때까지의 모든 요소를 리턴함

 

count(start=0 , step=1)

     - 시작 값과 증가값을 받아 무한히 증가하는 제너레이터 생성

from itertools import count

for i in count(10):
    if i > 20 :
        break
    else:
        print(i)
        
        
  =======Result========
10
11
12
13
14
15

 

permutations() 

  - 순열 (순서를 정해서 나열한 것) 

from itertools import permutations

test = ['a','b','c']

print(list(permutations(test,2)))


=====RESULT============

[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

 3개 문자중 2개 의 순열  

 

 

 

combinations() 

   - 조합 ( 서로 다른 n개에서 순서를 생각하지 않고 r를 뽑는 것) 

from itertools import combinations

test = ['a','b','c']

print(list(combinations(test,2)))


======RESULT========
[('a', 'b'), ('a', 'c'), ('b', 'c')]

3개 문자중 2개 의 조합 

 

 

product()

  -  곱집합 (여러 집합들 간에 하나씩 뽑아 조합을 만들 수 있는 모든 수) 

from itertools import product

test = ['a','b','c']

print(list(product(test,repeat=2)))


=====Result====
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'),
('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]

 

 

Reference 

https://www.blog.pythonlibrary.org/2016/04/20/python-201-an-intro-to-itertools/

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함