2 回答
TA贡献1998条经验 获得超6个赞
将所有成分类别放入一个结构中,并循环遍历它们:
vegetables = {"cucumber", "lettuce", "onion", "potato", "carrot"}
meats = {...}
carbs = {...}
dairy = {...}
all_categories = {
"vegetables": vegetables,
"meats": meats,
"carbs": carbs,
"dairy": dairy,
}
for ingredient in pizza_ingredients:
for category_name, category_items in all_categories.items():
if ingredient in category_items:
print(category_name)
如果你不需要category_name,定义all_categories为列表而不是字典
TA贡献1818条经验 获得超3个赞
Python 不知道你的集合是互斥的。因此,需要 elif。如果您愿意通过将元素映射到它们的集合名称来预先计算它们的分离,那么您可以删除 elif。喜欢:
X = {1,2,3}
Y = 'abc'
ALL = {1:"X",2:"X",3:"X",'a':'Y','b':'Y','c':'Y'}
for i in ingredients:
name_of_set = ALL[i]
添加回答
举报