如何从列表中的字符串字母生成所有可能的组合

How to generate all possible combinations from the letters of strings in a list

我试图从列表中的字符串字母生成所有可能的组合。

例如:

Input: ['jkl', 'ghi', 'def']
Output: ["jgd", "jge", "jgf", "jhd", "jhe", "jhf", "jid", "jie", "jif"...]
lst = ['jkl', 'ghi', 'def']

import itertools
list(map("".join, itertools.product(*lst)))

# result:
['jgd',
 'jge',
 'jgf',
 'jhd',
 'jhe',
 'jhf',
 'jid',
 'jie',
 'jif',
 'kgd',
 'kge',
 'kgf',
 'khd',
 'khe',
 'khf',
 'kid',
 'kie',
 'kif',
 'lgd',
 'lge',
 'lgf',
 'lhd',
 'lhe',
 'lhf',
 'lid',
 'lie',
 'lif']

我可以向你推荐一个简单的算法来做同样的事情,它使用递归:

def associations(entry):
    while len(entry) > 2:
        to_treat_later = entry.pop()
        print(f"We will treat {to_treat_later} later")
        entry = associations(entry)
        entry.append(to_treat_later)
    else:
        print(f"we can start with {entry}")
        associated_entry = []
        for elt_1 in entry[0]:
            for elt_2 in entry[1]:
                associated_entry.append(f"{elt_1}{elt_2}")
        return [associated_entry]


def convert_entry(entry):
    converted_entry = []
    for elt in entry:
        list_elt = []
        for letter in elt:
            list_elt.append(letter)
        converted_entry.append(list_elt)
    return converted_entry


the_entry = ["jkl", "ghi", "def", "cfe"]
associations(convert_entry(the_entry))