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

如何生成两个列表的全组合?适配大列表的代码实现需求

实现形容词与名词的全组合生成

嘿,这个需求本质上就是要生成两个列表的笛卡尔积(也就是所有可能的形容词+名词配对),然后把每个配对格式化成你要的"The 形容词 名词"样式对吧?不管你的列表多大,这几种Python方案都能轻松搞定:

方法1:嵌套循环(新手友好,逻辑直观)

这种写法最容易理解,就是先遍历每个形容词,再遍历每个名词,逐个组合:

noun = ["Whispers", "Loners", "Gamblers"]
adj = ["Shining", "Moaning"]

result_list = []
for adjective in adj:
    for noun_word in noun:
        result_list.append(f"The {adjective} {noun_word}")

# 如果你需要用顿号分隔的字符串输出,就用join方法
print("、".join(result_list))

方法2:用itertools.product(高效处理大列表)

Python标准库的itertools.product专门用来生成多个可迭代对象的笛卡尔积,代码更简洁,处理超大列表时效率也更高:

import itertools

noun = ["Whispers", "Loners", "Gamblers"]
adj = ["Shining", "Moaning"]

# 生成所有(形容词, 名词)的配对组合
all_combinations = itertools.product(adj, noun)
# 格式化每个配对
result_list = [f"The {a} {n}" for a, n in all_combinations]
# 输出结果
print("、".join(result_list))

方法3:列表推导式(一行搞定,简洁优雅)

如果喜欢更紧凑的写法,用嵌套列表推导式可以一步生成结果列表:

noun = ["Whispers", "Loners", "Gamblers"]
adj = ["Shining", "Moaning"]

result_list = [f"The {a} {n}" for a in adj for n in noun]
print("、".join(result_list))

这三种方法最终都会输出你想要的结果:The Shining Whispers、The Shining Loners、The Shining Gamblers、The Moaning Whispers、The Moaning Loners、The Moaning Gamblers,而且不管你的adj和noun列表有多少元素,都能自动生成所有可能的组合哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:22:11