首页 > 解决方案 > 如何生成 3 个字符前缀的唯一列表

问题描述

如何在 python 3 中将顶部列表添加到以下输出:

['abc', 'def', 'ghi']


['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']

如果可能的话,可以使用 for 循环来解决这个问题吗?

标签: pythonlistcombinations

解决方案


您正在寻找itertools.product

from itertools import product

lst = ['abc', 'def', 'ghi']

print( [''.join(c) for c in product(*lst)] )

印刷:

['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']

推荐阅读