簡體   English   中英

使用python從單詞列表中找到長度為2的單詞的所有組合

[英]Finding all combinations of words of length 2 from list of words using python

    temp1 = []
    filtered_tokens = ['once','upon','a','time','in','the','forest']
    for i in range(len(filtered_tokens)):
        for j in range(i+1,len(filtered_tokens)):
            temp1.append(filtered_tokens[i]+' '+filtered_tokens[j])

filetered_list ,在上面的代碼中包含10,000個單詞,我只給出了示例列表。

我需要的輸出:一次,一次,一次,一次,一次森林,一次,一次,一次,一次,一次,一次,一次,一次,一次,一次,一次,一次,一次時間,時間森林,在森林中,森林

當我編寫邏輯並運行它時,編譯器在運行時向我拋出內存不足異常。

請幫助我如何使用組合或任何其他python語言解決此問題。

謝謝

對於組合,可以使用itertools模塊。

import itertools
temp1 = itertools.combinations(filtered_tokens, 2)

將創建2個單詞的所有組合。 如果您想要列表,只需轉換生成器:

temp1 = list(temp1)

暫無
暫無

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

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