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

如何调用rdict辅助函数转换数据格式适配Python extract函数要求

解决方案

错误原因

你之前的写法存在两个问题:

  • rdict 函数的入参要求是完整的原始食谱字符串列表,你传入data[r]属于参数传错
  • 原始输入的data是列表类型,只能用数字下标取值,你直接用食谱名字符串r作为下标访问列表,自然会抛出String is not subscriptable报错。

修改方法

只需在extract函数入口处,先将传入的原始列表类型的data通过rdict转换为要求的嵌套字典格式即可,原有业务逻辑不需要改动:

def rdict(recipes):
    recipes_splitted = {}
    for r in recipes:
        recipe_name, parts = r.split(":")
        recipe_parts = {}
        for part in parts.split(','):
            product, number = part.split('*')
            recipe_parts[product] = int(number)
        recipes_splitted[recipe_name] = recipe_parts
    return recipes_splitted

def extract(recipes, data):
    # 新增代码:先把原始data转成嵌套字典格式
    data = rdict(data)
    result = []
    for r in recipes:
        tmp = []
        for key in data[r]:
            tmp.append(f"{key}:{data[r][key]}")
        final_string = ""
        for i in range(len(tmp)):
            if i < len(tmp) - 1:
                final_string += tmp[i] + ", "
            else:
                final_string += tmp[i]
        result.append(final_string)
    return result

测试运行

用你提供的示例输入直接调用即可:

print(extract(recipes = ['T-Bone', 'Green Salad1'],data = ["Pork Stew:Cabbage*5,Carrot*1,Fatty Pork*10",
"Green Salad1:Cabbage*10,Carrot*2,Pineapple*5",
"T-Bone:Carrot*2,Steak Meat*1"]
))

运行输出结果为:

['Carrot:2, Steak Meat:1', 'Cabbage:10, Carrot:2, Pineapple:5']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:09:04