本文介绍了如何使用itertools以字符串形式打印所有可能的组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些天我正在亲自学习Python.我对python代码有疑问.

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"

在这种情况下,变量A 可以选择两个选项,'can''cannot'.另外,变量B 可以选择两个选项,1315.我不想自己使用这些选项.我不知道如何自动选择两个选项.

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.

如果可以自动运行,我想使用itertools模块.我想要使​​用组合"的结果来做到这一点.

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.

推荐答案

首先,您想找到(can/cannot)和(13/15)的所有组合.

First, you would like to find all the combinations of (can/cannot) and (13/15).

为此,您可以使用:

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']

或者,按照@Olvin Roght的建议,您可以使用模板和starmap:

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

这篇关于如何使用itertools以字符串形式打印所有可能的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:32
查看更多