【发布时间】:2020-11-17 01:17:21
【问题描述】:
以这本矿物质词典为例,以及包含这些矿物质的食物作为矿物质:食物键:值对 (D)-
D = {'copper': {'Tomatoes', 'Onions', 'Eggplant', 'Grapes', 'Bell Peppers'}, 'manganese': {'Tomatoes', 'Onions', 'Eggplant', 'Grapes', 'Garlic', 'Celery', 'Bell Peppers'}, 'magnesium': {'Onions'}, 'phosphorus': {'Onions'}, 'potassium': {'Celery', 'Tomatoes', 'Grapes'}, 'sodium': {'Celery', 'Butter'}, 'salt': {'Celery', 'Butter'}}
我正在尝试编写一个函数(我现在假设是一个正则表达式),它接受 3 种矿物质的字符串,并返回包含这些矿物质的食物的 set。
例如,对于输入:'copper & manganese & phosphorus'
我需要输出为:{Onions}
因为洋葱是唯一含有所有 3 种矿物质的食物。 (使用 AND(不是 OR)逻辑)。
所以我只需要检查字典中包含所有 3 个值的键。
现在我能够想出以下内容,它只使用“OR”逻辑即可满足我的要求。如,它返回包含任何这些值的所有键。
D = {'copper': {'Tomatoes', 'Onions', 'Bell Peppers', 'Eggplant', 'Grapes'}, 'manganese': {'Tomatoes', 'Onions', 'Bell Peppers', 'Celery', 'Eggplant', 'Garlic', 'Grapes'}, 'magnesium': {'Onions'}, 'phosphorus': {'Onions'}, 'potassium': {'Tomatoes', 'Celery', 'Grapes'}, 'sodium': {'Butter', 'Celery'}, 'salt': {'Butter', 'Celery'}}
mList = ['copper', 'magnesium', 'manganese', 'phosphorus', 'potassium', 'salt', 'sodium']
x = []
y = [D[k] for k in mList if k in D]
for s in y:
for r in s:
if r not in x:
x.append(r)
x = sorted(x)
sx = set(x)
return(sx)
返回:
{'Tomatoes', 'Onions', 'Bell Peppers', 'Celery', 'Eggplant', 'Garlic', 'Grapes'}
【问题讨论】:
标签: python python-3.x regex