2014-07-08 2 views
1
template = "{{ person }} is a {{ quality }} {{ occupation }}" 
replacements = { 
"person":["John","Matt","Steve"], 
"quality":["great","dedicated"], 
"occupation":["engineer","student","athelete"] 
} 

Output: 
John is a great engineer 
Matt is a great engineer 
Steve is a great engineer 
John is a dedicated engineer 
Matt is a dedicated engineer 
Steve is a dedicated engineer 
John is a great student 
Matt is a great student 
Steve is a great student 
............................. 

교체 가능 요소 목록을 사용하여 순열을 생성 한 다음 목록 요소를 결합하여 루프를 생성 할 수 있습니다.문자열에서 가능한 문자열 치환의 모든 순열을 생성하는 파이썬 모듈?

list_input =  [["John","Matt","Steve"],["is"],["a"],["great","dedicated"],["engineer","student","athelete"]] 

example_permutation = ["John","is","a","great","engineer"] 

유사한 순열을 생성 할 수있는 파이썬 모듈/방법이 있습니까? 는 IS

+2

(제안) 목록

import itertools list_input = [["John","Matt","Steve"],["is"],["a"],["great","dedicated"],["engineer","student","athelete"]] for element in itertools.product(*list_input): print element 

또는 당신이 당신의 DICT의 @dano에서 직접 할 수있는이 단지 cartesian product, 원하는 모듈. :/ – geoffspear

+0

@Wooble, itertools에 지원 방법이 있는지 확실하지 않았지만, 순열을 생성하는 itertools 만 알았지 만,이 경우에는 데카르트 제품이라고 생각하지 않았습니다. – DhruvPathak

답변

4

심지어`와 itertools`을이 태그를 추가 한

replacements = { 
"person":["John","Matt","Steve"], 
"quality":["great","dedicated"], 
"occupation":["engineer","student","athelete"] 
} 

for element in itertools.product(*replacements.values()): 
    print("{} is a {} {}".format(*element)) 


#output 

John is a great engineer 
John is a great student 
John is a great athelete 
John is a dedicated engineer 
John is a dedicated student 
John is a dedicated athelete 
Matt is a great engineer 
Matt is a great student 
Matt is a great athelete 
Matt is a dedicated engineer 
Matt is a dedicated student 
Matt is a dedicated athelete 
Steve is a great engineer 
Steve is a great student 
Steve is a great athelete 
Steve is a dedicated engineer 
Steve is a dedicated student 
Steve is a dedicated athelete 
+1

itertools.product (* replacements.values ​​()) : 요소에'for for '를 사용하면 OP가 직접 데이터 구조에 적용 할 수 있습니다. – dano

+0

@dano yes 나는 그것을 추가 할 것이다 –

+0

그리고 나서'print' 문은'print ("{}는 {} {}"형식 (* 요소))'가되어 원하는 출력을 얻는다. – dano