簡體   English   中英

如何使用 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可以選擇兩個選項, 1315 我不想自己使用這些選項。 我不知道如何自動選擇兩個選項。

如果可以自動,我想使用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)))

它是如何工作的?

  1. 我們使用itertools.product()得到兩個列表的笛卡爾積;
  2. 我們將先前操作的結果直接重定向到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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM