본문 바로가기
Tip/Python

[Python] "combinations", 리스트 원소들의 조합 구하기

by frog 2021. 10. 9.

[Python] "combinations", 리스트 원소들의 조합 구하기


 내용

  • python에서 List의 원소들로 조합을 만들 수 있다.
  • itertools 의 combinations 함수를 사용한다.
  • n개의 숫자에서 r개의 숫자를 골라서 만들 수 있는 모든 경우의 수를 구해준다.
# combination 함수 import
from itertools import combinations

# 조합을 만들 list
candidate = [1, 2, 3]


# 사용법
# combinations(list, number)
# list : 조합을 만들 list
# number : 몇 개의 숫자를 뽑아 조합을 만들 것인지
result = list(combinations(candidate, 2)) # [(1,2),(1,3),(2,3)]

댓글