Python中不完全展平嵌套列表并生成所有组合的实现方法
解决方案
你可以利用itertools.product来生成所有可能的组合,核心是先把原列表中的元素统一处理为可迭代对象:
遍历
items中的每个元素:- 如果是字符串,将其包装为只包含该字符串的单元素列表(避免被拆分为单个字符)
- 如果是嵌套列表,直接保留原结构
用
itertools.product对处理后的可迭代对象生成笛卡尔积,这会自动枚举所有可能的组合将每个组合元组用空格拼接成完整字符串
代码实现
import itertools items = ['Hello', ['Ben', 'Chris', 'Linda'], '! The things you can buy today are', ['Apples', 'Oranges']] # 预处理每个元素,统一为可迭代对象 processed = [item if isinstance(item, list) else [item] for item in items] # 生成笛卡尔积并拼接成字符串 new_list = [' '.join(combination) for combination in itertools.product(*processed)] print(new_list)
输出结果
['Hello Ben ! The things you can buy today are Apples', 'Hello Ben ! The things you can buy today are Oranges', 'Hello Chris ! The things you can buy today are Apples', 'Hello Chris ! The things you can buy today are Oranges', 'Hello Linda ! The things you can buy today are Apples', 'Hello Linda ! The things you can buy today are Oranges']
这种方法无需硬编码迭代逻辑,不管items里的元素数量、嵌套列表数量如何变化,都能自动适配。
内容的提问来源于stack exchange,提问作者Alison LT
相关产品推荐
相关产品推荐

