You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中不完全展平嵌套列表并生成所有组合的实现方法

解决方案

你可以利用itertools.product来生成所有可能的组合,核心是先把原列表中的元素统一处理为可迭代对象:

  1. 遍历items中的每个元素:

    • 如果是字符串,将其包装为只包含该字符串的单元素列表(避免被拆分为单个字符)
    • 如果是嵌套列表,直接保留原结构
  2. 用itertools.product对处理后的可迭代对象生成笛卡尔积,这会自动枚举所有可能的组合

  3. 将每个组合元组用空格拼接成完整字符串

代码实现

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 19:20:35