티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to get the Cartesian product of multiple lists

여러 리스트의 카르테시안 곱을 얻는 방법

 문제 내용 

How can I get the Cartesian product (every possible combination of values) from a group of lists?

여러 개의 리스트에서 가능한 모든 조합(카테시안 곱)을 어떻게 구할 수 있을까요?

 

For example, given

예를 들어, 다음이 주어졌다고 가정해봅시다.
somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]

 

How do I get this?

어떻게 하면 이를 구할 수 있을까요?
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5), ...]

 


One common application for this technique is to avoid deeply nested loops. See Avoiding nested for loops for a more specific duplicate. Similarly, this technique might be used to "explode" a dictionary with list values; see Combine Python Dictionary Permutations into List of Dictionaries .

이 기술의 일반적인 응용은 깊게 중첩된 루프를 피하는 것입니다. 더 구체적인 중복 사례에 대해서는 중첩된 for 루프 피하기를 참조하십시오. 마찬가지로, 이 기술은 목록 값을 갖는 사전을 "폭발"시키는 데 사용될 수 있습니다. Python 딕셔너리 순열을 딕셔너리 목록으로 결합을 참조하십시오.

 

If you want a Cartesian product of the same list with itself multiple times, itertools.product can handle that elegantly. See Operation on every pair of element in a list or How can I get "permutations with repetitions" from a list (Cartesian product of a list with itself)?.

만약 동일한 리스트의 카르테시안 곱을 여러번 수행하려면, itertools.product를 사용하면 간단하게 처리할 수 있습니다. Operation on every pair of element in a list 나 How can I get "permutations with repetitions" from a list (Cartesian product of a list with itself)?를 참조하세요.

 

Many people who already know about itertools.product struggle with the fact that it expects separate arguments for each input sequence, rather than e.g. a list of lists. The accepted answer shows how to handle this with *. However, the use of * here to unpack arguments is fundamentally not different from any other time it's used in a function call. Please see Expanding tuples into arguments for this topic (and use that instead to close duplicate questions, as appropriate).

itertools.product를 이미 알고 있는 많은 사람들이 입력 시퀀스마다 별도의 인수를 예상하는 데 어려움을 겪습니다. 예상대로 리스트의 리스트를 사용하는 대신 *를 사용하여 이를 처리하는 방법이 받아들여졌습니다. 그러나 *를 인수를 언패킹하기 위해 여기에서 사용하는 것은 함수 호출에서 다른 시간에 사용하는 것과 근본적으로 다르지 않습니다. 이 주제에 대해서는 "튜플을 인수로 확장하기"를 참조하십시오(적절한 경우 중복 질문을 닫을 때 대신 사용하십시오).

 

 

 

 높은 점수를 받은 Solution 

Use itertools.product, which has been available since Python 2.6.

Python 2.6부터 사용 가능한 itertools.product를 사용하세요.
import itertools

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]
for element in itertools.product(*somelists):
    print(element)

 

This is the same as:

이는 다음과 같습니다:
for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
    print(element)

 

 

 가장 최근 달린 Solution 

Recursive Approach:

재귀적인 방법:
def rec_cart(start, array, partial, results):
  if len(partial) == len(array):
    results.append(partial)
    return 

  for element in array[start]:
    rec_cart(start+1, array, partial+[element], results)

rec_res = []
some_lists = [[1, 2, 3], ['a', 'b'], [4, 5]]  
rec_cart(0, some_lists, [], rec_res)
print(rec_res)

 

Iterative Approach:

반복적 접근 방식:
def itr_cart(array):
  results = [[]]
  for i in range(len(array)):
    temp = []
    for res in results:
      for element in array[i]:
        temp.append(res+[element])
    results = temp

  return results

some_lists = [[1, 2, 3], ['a', 'b'], [4, 5]]  
itr_res = itr_cart(some_lists)
print(itr_res)

 

 

출처 : https://stackoverflow.com/questions/533905/how-to-get-the-cartesian-product-of-multiple-lists

반응형
댓글
공지사항
최근에 올라온 글