2017-05-16 1 views
2

두 문자열의 모든 조합을 인쇄하려고합니다.가능한 모든 문자열 조합을 생성하십시오.

attributes = "old green".split() 
persons = "car bike".split() 

나는 무엇을 기대 : 지금까지 시도 무엇

old car 
old bike 
green car 
green bike 

가 :

from itertools import product 

attributes = "old green".split() 
persons = "car bike".split() 

print([list(zip(attributes, p)) for p in product(persons,repeat=1)]) 
+1

당신이 예에서 입력이라고 생각합니까? 말? 공백으로 구분됩니까? 투입물은 어떤 형태를 취할 수 있습니까? _ 특이하다. 그리고 시도를 잘못한 것이 무엇입니까? 어떤 문제가 발생 했습니까? 무엇을 고치려고 했습니까? 어떤 문서를 읽었습니까? –

답변

1

당신은 지능형리스트로이 작업을 수행 할 수 있습니다. 이것은 이것이 운동의 끝인 경우에 효과적입니다. 단어의 다른 목록을 추가하기를 원한다면 다른 방법이 필요합니다.

>>> [p for p in product(attributes, persons)] 
[('old', 'car'), ('old', 'bike'), ('green', 'car'), ('green', 'bike')] 

다음 이러한 문자열 연결할 : 당신은 당신이 사용할 수있는 개별적으로 인쇄 할 경우

>>> [' '.join(p) for p in product(attributes, persons)] 
['old car', 'old bike', 'green car', 'green bike'] 

[elem + ' ' + elem2 for elem in attributes for elem2 in persons] 
2

당신은 personsattributesproduct에 합격해야 목록 이해 대신 for -loop :

for p in product(attributes, persons): 
    print(' '.join(p)) 
1

당신은 같은 두 개의 for 루프를 사용할 수 있습니다

attributes = ['old', 'green'] 
persons = ['car', 'bike'] 
for x in attributes: 
    for y in persons: 
     print x, y 

출력 :

old car 
old bike 
green car 
green bike