본문 바로가기
프로그래밍/python

[python] 조합(combinations) 기초 & 조합 사용법

by 잇서니 2019. 9. 6.
반응형

 

 

조합 (combinations)


언제 사용할까?

    • 2차원 배열이 있다고 하자.
      • [[1,"sunny","music"],[2,"hi","math"],[3,"bye","math"]]
      • 컬럼 개수 별로 모든 쌍을 구해야 하는 경우 요긴하게 쓰인다.
        • 1개쌍 : (1,) / ('sunny',) / (2,) / ('hi',) / (3,) / ('bye',)
        • 2개쌍 : (1,"sunny"), (1,"music"),("sunny","music") / ... / (3,"bye"),(3,"mail"),("bye","mail")
        • 3개쌍 : (1,"sunny","music") / ... / (3,"bye","math")
      • 예를 들어 학번,이름,전공이 주어진 2차원 배열이 주어졌다. (학번,이름), (학번,전공), (이름,전공), (학번,이름,전공)의 조합을 뽑을 필요가 있을 때 사용한다.

조합은 어떻게 만들까?

from itertools import combinations

university=[[1,"sunny","music"],[2,"hi","math"],[3,"bye","math"]]

result=[]
result_2=[]

# 1개쌍,2개쌍,3개쌍 / 1개쌍,2개쌍,3개쌍 / ...
for i in university:
	for j in range(1, len(university[0]) + 1):
		c=combinations(university[i],j)
		result.extend(c)

# 1개쌍 쭈우우우욱 / 2개쌍 쭈우우우욱 / 3개쌍 쭈우우욱
for i in range(1,len(university[0])+1):
	for j in university:
		c=combinations(j,i)
		result_2.extend(c)

 

      • combinations(data,num)
        • data : 리스트, 튜플, 딕셔너리, set, 문자열 등 조합을 뽑고 싶은 data를 입력
        • num : data 값에서 몇 개 쌍으로 이루어진 조합을 뽑고 싶은지

조합 결과 활용하기

      • 조합은 object 형태로 출력된다.
from itertools import combinations

a=[1,2,3]

c=combinations(a,2)
print(c)

 

      • 그러니 조합결과를 리스트에 extend하여 사용하자.
lst=[]
lst.extend(c)
print(lst)

#[(1,2),(1,3),(2,3)]

 

리스트 append 와 extend 차이

      • append
        • 통째로 추가됨
        • object가 추가되는 방식
      • extend
        • 하나씩 추가됨
        • element가 추가되는 방식

a=[1,2,3]
plus=[4,5]

a.append(plus)
# a = [1,2,3,[4,5]]

a.extend(plus)
# a = [1,2,3,4,5]

 

 

반응형

댓글