簡體   English   中英

從 python 中的給定單詞列表創建所有可能組合的列表

[英]creating a list of all possible combination from a given list of words in python

我在創建給定單詞列表的所有可能組合的列表時遇到問題。 結果應該是每行所有可能單詞的組合。 組合的最大長度基於輸入文件中給出的單詞數量。 這意味着,如果文件包含 7 個單詞,則組合最長為 7 個單詞。 output 的格式應如下所示:

德國德國德國德國德國德國德國德國西班牙德國德國德國德國西班牙

等等等等

我用谷歌搜索了一下,發現 itertools 對我來說是一個可能的解決方案。

給定的單詞位於名為 input.txt 的文件中

我在這里使用了堆棧溢出條目中的這段代碼:

如何獲得列表元素的所有可能組合?

我只是將主要部分表示為文件讀取部分,文件 output 不是這里問題的一部分。

所以我給出的單詞列表是:德國西班牙阿爾巴尼亞荷蘭

哪個工作正常

from itertools import combinations


features = ['germany', 'spain', 'albania']
tmp = []
for i in range(len(features)):
    oc = combinations(features, i + 1)
    for c in oc:
        tmp.append(list(c))
print (tmp)

output 與預期不符。

因為我的列表包含 3 個詞,所以我更改了代碼:

德國 西班牙 阿爾巴尼亞

哪個工作正常

from itertools import combinations


features = ['germany', 'spain', 'albania']
tmp = []
for i in range(len(features)):
    oc = combinations(features, i + 1)
    for c in oc:
        tmp.append(list(c))
print (tmp)

但是,我相信結果並不像預期的那樣,它應該是所有可能的組合。 缺少一些組合,例如:

germany
germany germany
germany germany spain 
germany germany germany 

或者其他的東西。

(output 限制為 3,因為給定的列表在原始問題中包含 3 個單詞)。

我如何將 germany germany 等組合獲取到 output,為什么它們不見了? 我相信當我使用數字作為別針或其他東西時,我應該有同樣的問題。 它不能從 0 到 9999 開始,但列表中也應該有 00、000 和 0000。

最好的問候弗雷德

我相信您想使用 function combinations_with_replacement

from itertools import combinations_with_replacement


features = ['germany', 'spain', 'albania']
tmp = []
for i in range(len(features)):
    oc = combinations_with_replacement(features, i + 1)
    for c in oc:
        tmp.append(list(c))
print (tmp)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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