Python食谱URL按食材分类问题:代码输出空列表求排查
问题修复方案
核心错误分析
你的代码输出空列表是因为判断逻辑完全颠倒:
if link in fruitwords:这是检查整个URL字符串是否存在于fruitwords列表中,显然所有URL都不在这个列表里,所以fruit永远为空。if link in appleWord:这是检查URL字符串是否是apple这个单词的子串,实际应该是检查apple是否是URL的子串,也就是appleWord in link。
修复后的基础代码
recipes = ["example.com/cherry-pie/", "example.com/caramel-apples/", "example.com/blueberry-banana-bread/", "example.com/apple-fruit-salad/"] fruit = [] apple = [] banana = [] blueberry = [] cherry = [] def fruitLoop(): for link in recipes: # 检查是否包含任意水果相关关键词,加入fruit列表 if any(word in link for word in ["fruit", "apple", "banana", "blueberry", "cherry"]): fruit.append(link) # 单独检查各食材关键词 if "apple" in link: apple.append(link) if "banana" in link: banana.append(link) if "blueberry" in link: blueberry.append(link) if "cherry" in link: cherry.append(link) print(fruit) print(apple) print(banana) print(blueberry) print(cherry) fruitLoop()
运行后会得到你预期的输出:
["example.com/cherry-pie/", "example.com/caramel-apples/", "example.com/blueberry-banana-bread/", "example.com/apple-fruit-salad/"] ["example.com/caramel-apples/", "example.com/apple-fruit-salad/"] ["example.com/blueberry-banana-bread/"] ["example.com/blueberry-banana-bread/"] ["example.com/cherry-pie/"]
更通用的优化方案(适合长列表+多分类场景)
如果实际食谱列表很长且分类不止水果,建议用字典管理分类规则,避免重复代码:
recipes = ["example.com/cherry-pie/", "example.com/caramel-apples/", "example.com/blueberry-banana-bread/", "example.com/apple-fruit-salad/", "example.com/egg-noodles/"] # 定义分类规则:键是分类名,值是该分类对应的关键词列表 category_rules = { "fruit": ["fruit", "apple", "banana", "blueberry", "cherry"], "apple": ["apple"], "banana": ["banana"], "blueberry": ["blueberry"], "cherry": ["cherry"], "egg": ["egg"] # 新增其他分类示例 } # 初始化分类结果字典 category_results = {cat: [] for cat in category_rules.keys()} def categorize_recipes(): for link in recipes: for category, keywords in category_rules.items(): if any(keyword in link for keyword in keywords): category_results[category].append(link) # 打印结果 for cat, items in category_results.items(): print(f"{cat}: {items}") categorize_recipes()
这种方式新增分类只需要修改category_rules字典,不用额外写判断逻辑,扩展性更强。
内容的提问来源于stack exchange,提问作者discollection
相关产品推荐
相关产品推荐

