Python查询字典中所有相同值对应键时仅返回首个结果的问题
问题解答
错误原因
你的代码在if cont == containers的判断块里直接执行了return matching_recipes,程序第一次匹配到符合条件的食谱完成追加操作后,就会直接触发函数返回,终止整个循环和函数运行,因此不会遍历字典剩下的元素。
修正后的代码
recipes = {'Fixate Pasta E Fagioli' : '1G1Y1t' , 'Fixate Vegan Quinoa with Winter Veggies' : '1G1Y1t' , 'Fixate Balsamic Mushroom Toast' : '1G1Y1t' } def get_recipe(cont): matching_recipes = [] for recipe, containers in recipes.items(): if cont == containers: matching_recipes.append(recipe) return matching_recipes if matching_recipes else 'no matching recipe' print(get_recipe('1G1Y1t'))
核心修改点
- 将
matching_recipes移到函数内部作为局部变量,避免多次调用函数时全局变量累计旧结果导致逻辑错误 - 将
return语句移出循环体,等待字典全部元素遍历完成后再统一返回最终的匹配结果
运行修正后的代码,传入'1G1Y1t'参数即可得到全部3个匹配的食谱列表。
内容的提问来源于stack exchange,提问作者mlkurek711
相关产品推荐
相关产品推荐

