Reputation: 43
I am studying Python personally these days. I have a question about python code.
A = "I " + (can/cannot) + " fly"
B = "I am " + (13/15) + " years old"
In theses cases, variable A
can select two options, 'can'
or 'cannot'
.
Also, variable B
can select two options, 13
or 15
.
I don't want to use these options myself.
I don't know how to select two options automatically.
If it can be automatically, I want to use itertools
module.
I want result using "combinations" to do this.
C = [(I can fly I am 13 years old) , (I can fly I am 15 years old) , (I cannot fly I am 13 years old) , (I cannot fly I am 15 years old)]
If anyone who can help me with this code, please help.
Upvotes: 0
Views: 354
Reputation: 1795
First, you would like to find all the combinations of (can/cannot) and (13/15).
To do this you can use:
import itertools
can_or_cannot = ['can', 'cannot']
age = [13, 15]
list(itertools.product(can_or_cannot, age))
Out[13]: [('can', 13), ('can', 15), ('cannot', 13), ('cannot', 15)]
Now you can use list comprehension:
C = [f"I {can_or_cannot} fly I am {age} years old" for (can_or_cannot, age) in list(itertools.product(can_or_cannot, age))]
Out[15]:
['I can fly I am 13 years old',
'I can fly I am 15 years old',
'I cannot fly I am 13 years old',
'I cannot fly I am 15 years old']
Or, as suggested by @Olvin Roght, you can use a template and starmap
:
from itertools import product, starmap
template = 'I {} fly I am {} years old'
result = list(starmap(template.format, product(can_or_cannot, age)))
Upvotes: 3
Reputation: 7812
For some reasons, @theletz decided to not include my recommendation into his answer, so I'll post it here:
from itertools import product, starmap
can_or_cannot = ['can', 'cannot']
age = [13, 15]
template = 'I {} fly I am {} years old'
result = list(starmap(template.format, product(can_or_cannot, age)))
How does it work?
itertools.product()
to get cartesian product of two lists;itertools.starmap()
, which execute str.format()
and pass unpacked pair as function arguments. Upvotes: 1
Reputation: 2076
You can try this:
fly = ["can","cannot"]
lst = []
for i in fly:
A = "I " + i + " fly"
for j in [13,15]:
B = " I am " + str(j) + " years old"
lst.append((A+B))
print(lst)
Upvotes: -2