我有一本字典:
meals = {'Pasta Bolognese' : ['pasta', 'tomato sauce', 'ground beef'],
'Cold Salad' : ['greens', 'tomato'],
'Warm Salad' : ['greens', 'tomato', 'corn', 'chickpeas', 'quinoa'],
'Sandwich' : ['bread', 'turkey slices', 'cheese', 'sauce']}
和一份清单:
ingredients = ['bread', 'chickpeas', 'tomato', 'greens']
我想从字典中获取一个键,如果它的所有值都在列表中。所以就目前的情况而言,我想要“冷沙拉”,因为“绿色”和“西红柿”都在列表中
您可以使用:
请注意,这段代码使用带有} 检查一个集合中的所有值是否都是另一个集合的子集
next
的生成器,也可以更有效地使用多个in
语句,而不是all
和带有in
的循环,我使用^{如果可能没有匹配项,请在末尾添加
None
:或者任何东西,您可以用任何东西来替换
None
,例如"No Match"
您可以使用列表理解,如下所示:
结果:
您会注意到我添加了
Another Item
来测试将返回多个匹配项相关问题 更多 >
编程相关推荐