简体   繁体   中英

How to print all possible combinations in string using itertools?

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.

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)))

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?

  1. We use itertools.product() to get cartesian product of two lists;
  2. Result of previous action we redirect directly to itertools.starmap() , which execute str.format() and pass unpacked pair as function arguments.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM