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

Python实现可变数量可变长度列表的元素全组合字符串拼接

解决方案

Python 标准库内置的 itertools.product 可直接处理可变数量、可变长度列表的笛卡尔积计算,无需手动编写嵌套循环,适配任意场景的全组合需求。

完整实现代码

from itertools import product

# 示例子列表,数量和长度可任意调整
list1 = ["text11","text12", "text13"]
list2 = ["text21","text22", "text23"]
list3 = ["text31","text32"]

# 所有子列表存入总列表,可动态增删子列表
total_list = [list1, list2, list3]

# 计算全组合并按要求拼接字符串
list_final = [" + ".join(combo) for combo in product(*total_list)]

代码说明

  • product(*total_list) 中的*是参数解包操作,会自动把总列表中的所有子列表作为独立参数传入笛卡尔积计算函数,不管总列表中有多少个子列表都可正常运行
  • 函数返回的每个笛卡尔积结果是对应位置元素组成的元组,直接用" + ".join()即可拼接为要求的字符串格式
  • 最终生成的list_final完全符合你需要的输出格式

如果不想依赖标准库,也可以用递归逻辑自己实现全组合计算:

def calc_all_combo(total_list, temp_combo=None):
    if temp_combo is None:
        temp_combo = []
    # 所有列表遍历完成,返回拼接后的字符串
    if not total_list:
        yield " + ".join(temp_combo)
        return
    # 取第一个列表和剩余列表做递归
    current_list = total_list[0]
    remain_lists = total_list[1:]
    for item in current_list:
        yield from calc_all_combo(remain_lists, temp_combo + [item])

# 调用方法
list_final = list(calc_all_combo(total_list))

内容的提问来源于stack exchange,提问作者AlbaTroels

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:45:02