简体   繁体   中英

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 , in the above code contains 10,000 words, i only gave the sample list.

output needed for me: once upon, once a, once in, once the, once forest, upon a, upon time, upon in, upon the, upon forest, a time, a in, a the, a forest, time in, time the, time forest, in the, in forest, the forest

when i wrote the logic and run it, compiler thrown me Low memory exception at run time.

Please help me how i can solve this using Combinations or any other python language.

Thank You

For combinations you can use the itertools module.

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

will create all combinations of 2 words. If you want the list just convert the generator:

temp1 = list(temp1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM