![](/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.