![](/img/trans.png)
[英]Print 4 letter combinations of a string without using lists or itertools
[英]How to print all possible combinations in string using itertools?
这些天我正在亲自学习 Python。 我有一个关于 python 代码的问题。
A = "I " + (can/cannot) + " fly"
B = "I am " + (13/15) + " years old"
在这些情况下,变量A
可以选择两个选项, 'can'
或'cannot'
。 此外,变量B
可以选择两个选项, 13
或15
。 我不想自己使用这些选项。 我不知道如何自动选择两个选项。
如果可以自动,我想使用itertools
模块。 我想要使用“组合”来做到这一点的结果。
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)]
如果有人可以帮助我使用此代码,请提供帮助。
首先,您想找到 (can/cannot) 和 (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)]
现在您可以使用列表理解:
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
:
from itertools import product, starmap
template = 'I {} fly I am {} years old'
result = list(starmap(template.format, product(can_or_cannot, age)))
出于某些原因,@theletz 决定不将我的建议包含在他的回答中,因此我将其发布在这里:
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)))
它是如何工作的?
itertools.product()
得到两个列表的笛卡尔积;itertools.starmap()
,它执行str.format()
并将解压对作为函数参数传递。你可以试试这个:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.