Reputation: 41
I'm trying to print all combinations of two strings.
attributes = "old green".split()
persons = "car bike".split()
What I expect:
old car
old bike
green car
green bike
What I have tried so far:
from itertools import product
attributes = "old green".split()
persons = "car bike".split()
print([list(zip(attributes, p)) for p in product(persons,repeat=1)])
Upvotes: 2
Views: 622
Reputation: 152587
You have to pass persons
and attributes
to product
:
>>> [p for p in product(attributes, persons)]
[('old', 'car'), ('old', 'bike'), ('green', 'car'), ('green', 'bike')]
and then concatenate these strings:
>>> [' '.join(p) for p in product(attributes, persons)]
['old car', 'old bike', 'green car', 'green bike']
In case you want to print them individually you can use a for
-loop instead of the list comprehension:
for p in product(attributes, persons):
print(' '.join(p))
Upvotes: 3
Reputation: 5613
You can use two for loops like:
attributes = ['old', 'green']
persons = ['car', 'bike']
for x in attributes:
for y in persons:
print x, y
output:
old car
old bike
green car
green bike
Upvotes: 2
Reputation: 13955
You can do this with a list comprehension. This works if this is the end of the exercise. If you are hoping at some point to add another list of words then you will need a different method.
[elem + ' ' + elem2 for elem in attributes for elem2 in persons]
Upvotes: 2