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

Python函数开发:根据指定Item返回对应分类的Top3关联Item

解决方案

步骤1:解析DataFrame中的JSON数据

不要用字符串拼接的方式处理JSON,应该用json.loads解析每一行的JSON字符串,转换成结构化数据方便后续操作:

import pandas as pd
import json

# 构建原DataFrame
data = {
    "json_col": [
        '{"category":"a","items":["a","b","c","d","e","f"]}',
        '{"category":"b","items":["u","v","w","x","y"]}',
        '{"category":"c","items":["p","q"]}',
        '{"category":"d","items":["m"]}'
    ]
}
df = pd.DataFrame(data)

# 解析JSON列,生成结构化字典列表
parsed_data = [json.loads(row) for row in df['json_col']]

步骤2:实现目标函数

按照需求编写函数,逻辑清晰直接:

def item_list(parsed_data, item="a"):
    # 遍历所有分类数据
    for category_info in parsed_data:
        items_list = category_info["items"]
        if item in items_list:
            # 过滤掉自身,保留原顺序
            filtered_items = [i for i in items_list if i != item]
            # 返回前3个元素(不足3个则返回全部)
            return filtered_items[:3]
    # 找不到目标item时返回空列表
    return []

测试案例验证

运行以下代码验证所有规则:

# 测试输入"a"
print(item_list(parsed_data, "a"))  # 输出: ['b', 'c', 'd']

# 测试输入"w"
print(item_list(parsed_data, "w"))  # 输出: ['u', 'v', 'x']

# 测试输入"q"
print(item_list(parsed_data, "q"))  # 输出: ['p']

# 测试输入"m"
print(item_list(parsed_data, "m"))  # 输出: []

# 测试不存在的item"r"
print(item_list(parsed_data, "r"))  # 输出: []

可选扩展

如果需要在找不到item时抛出错误而非返回空列表,可修改函数末尾逻辑:

# 替换原返回空列表的代码
raise ValueError(f"Item '{item}' not found in any category")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 11:24:23