2014-04-07 2 views
0

의 모든 가능한 조합은이 같은 목록이 있습니다파이썬 3.3 : 목록

[['one', 'two', 'three', ...], ['a', 'b', ...], ['left', 'right'] ...] 

와 그 항목의 모든 가능한 조합을 만들고 같은 문자열에 넣어해야합니다

"one|a|left" 
"one|a|right" 
"one|b|left" 
"one|b|right" 
"two|a|left" 
"two|a|right" 
"two|b|left" 
... 

무엇 그것을하는 가장 쉬운 방법은 무엇입니까?

+0

https://docs.python.org/2/library/itertools.html#itertools.combinations를 확인하셨습니까? – fredtantini

+0

예 itertools를 시도하지만 필요한 방식으로 작동하지 않습니다 – Michal

+0

분명히 잘못된 기능을 가지고 있습니다 ... – fredtantini

답변

9

당신은 itertools.product 사용할 수 있습니다

from itertools import product 
lst = [['one', 'two', 'three'], ['a', 'b'], ['left', 'right']] 
print(list(product(*lst))) 

당신이 원하는 것을 있는지 확인

["|".join([p, q, r]) for p, q, r in product(*lst)] 

출력 :

[('one', 'a', 'left'), ('one', 'a', 'right'), ('one', 'b', 'left'), ('one', 'b', 'right'), ('two', 'a', 'left'), ('two', 'a', 'right'), ('two', 'b', 'left'), ('two', 'b', 'right'), ('three', 'a', 'left'), ('three', 'a', 'right'), ('three', 'b', 'left'), ('three', 'b', 'right')] 

당신이 설명 원하는 문자열을 생산하기

['one|a|left', 
'one|a|right', 
'one|b|left', 
'one|b|right', 
'two|a|left', 
'two|a|right', 
'two|b|left', 
'two|b|right', 
'three|a|left', 
'three|a|right', 
'three|b|left', 
'three|b|right'] 
+0

왜 그렇게 오래 걸립니까? 'map ("|".join, product (* lst)) "를 선호합니다. – Arpegius

+0

@Arpegius : Python 3에서 :'list (map (..))'를 사용하십시오. – jfs