python-3.x 匹配元组列表中的元素并移除该列表的元组元素

b4qexyjb  于 2023-03-24  发布在  Python
关注(0)|答案(2)|浏览(121)
recipes = [('Peanut Butter','200g salt','500g sugar'),('Chocolate Brownie', '500g flour')]

def remove_recipe(recipe_name,recipes):
    recipe_dict = dict(recipes)
    size = recipe_dict.get(recipe_name)
    if size is not None:
        recipe_dict.pop(recipe_name)
        updated_recipes = [(k, v) for k, v in recipe_dict.items()]
        return updated_recipes

    else:
        print("There is no such recipe.")

我想实现什么?嗨,我是python的新手,我试图从元组列表中删除一个项目。我将食谱列表转换为字典,并使用size为特定键的值。一旦键不是None,它将从字典中删除该项目并将其转换回列表。
收到的错误:值错误:字典更新序列元素#0的长度为3;2为必填项

7lrncoxx

7lrncoxx1#

我会说不需要转换为字典-假设元组的第一个元素是食谱的名称-只需使用列表解析并比较大小:

def remove_recipe(recipe_name,recipes):    
    res = [r for r in recipes if r[0] != recipe_name] # filter out by the recipe name
    
    if len(res) != len(recipes):
        print("Recipe removed.")
    else:
        print("There is no such recipe.")

    return res
avkwfej4

avkwfej42#

字典是一个有key:value对的结构。所以你不能把这个元组转换成一个dict,因为它不知道它应该做什么。你实际上不需要一个字典来做你想做的事情。

recipes = [('Peanut Butter','200g salt','500g sugar'),('Chocolate Brownie', '500g flour')]

def remove_recipe(recipe_name,recipes):
    for recipe in recipes:
        if recipe_name in recipe:
            recipes.remove(recipe)
            print("Recipe removed.")
            break

    else:
        print("There is no such recipe.")

一个dict可以构建你的食谱,但你必须重构你的食谱:

{
    "name": 'Peanut Butter',
    "ingredients": ['200g salt', '500g sugar']
}

相关问题