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

Python中如何从字典列表的tags字段提取值生成配对元组?

Python实现方案

核心思路:直接调用Python标准库itertools的combinations方法生成不重复的两两组合,遍历所有字典提取tags字段后合并结果即可,不需要手动写嵌套循环。

完整实现代码如下:

import itertools

# 原始数据
output = [
    {
        "title": "subject1",
        "tags": ['a','b'],
    },
    {
        "title": "subject2",
        "tags": ['c','d','f'],
    }
]

result = []
for item in output:
    # 提取tags字段,缺省返回空列表避免报错
    tags = item.get("tags", [])
    # 生成所有长度为2的不重复组合,追加到结果列表
    result.extend(itertools.combinations(tags, 2))

print(result)

运行后输出结果:

[('a', 'b'), ('c', 'd'), ('c', 'f'), ('d', 'f')]

注意:如果存在tags元素数量小于2的字典,combinations会自动返回空迭代器,不会抛出异常,对应项会被自动跳过。如果不需要元组自带的字符串引号,可以自行格式化输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:36:07