Python 巨蟒;搜索“;包含在多个键中的值的字典,正则表达式?
以这本矿物词典为例,将含有这些矿物的食物作为矿物:食物关键字:价值对(D)- 我正在尝试编写一个函数(我现在假设是一个正则表达式),它接受一个由3种矿物质组成的字符串,并返回一组含有这些矿物质的食物 例如,对于输入:Python 巨蟒;搜索“;包含在多个键中的值的字典,正则表达式?,python,python-3.x,regex,Python,Python 3.x,Regex,以这本矿物词典为例,将含有这些矿物的食物作为矿物:食物关键字:价值对(D)- 我正在尝试编写一个函数(我现在假设是一个正则表达式),它接受一个由3种矿物质组成的字符串,并返回一组含有这些矿物质的食物 例如,对于输入:“铜、锰和磷” 我需要输出为:{Onions} 因为洋葱是唯一含有三种矿物质的食物。(使用AND(非OR)逻辑) 所以我只需要检查字典中包含所有3个值的键 现在我能够想出下面的方法,只使用“或”逻辑就可以实现我想要的。与中一样,它返回包含这些值的所有键 D = {'copper':
“铜、锰和磷”
我需要输出为:{Onions}
因为洋葱是唯一含有三种矿物质的食物。(使用AND(非OR)逻辑)
所以我只需要检查字典中包含所有3个值的键
现在我能够想出下面的方法,只使用“或”逻辑就可以实现我想要的。与中一样,它返回包含这些值的所有键
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'}
所以只要稍微扩展一下,你们可以简单地使用集合的交点
符号和运算符将为您提供这些集合的交点,即这些集合都有共同点的任何项目
>>> D["copper"] & D["magnesium"]
{'Onions'}
这实际上只是一个简写:
>>> D["copper"].intersection( D["magnesium"] )
{'Onions'}
更进一步,您可以将其中三个组合起来:
>>> D["copper"] & D["manganese"] & D["phosphorus"]
{'Onions'}
它应该足够简单,您可以使用输入作为查找的字典键 正如Matt所指出的,Python集合允许您基于集合论执行计算:在本例中,检查集合之间的相交(或重叠)
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'}}
基于上述字典,接受三个参数的函数可以计算并返回字典中存储的三个集合的交集:
def food_intersection(3_mineral_string, D):
food1, food2, food3 = 3_mineral_string.split('_')
# i.e. 'copper_magnesium_phosphorus'
# The split function creates a list w/ 3 elements
# that list can be immediately 'unpacked'
# and each element can be associated w/ a
# separate variable (i.e. food1)
# Your technique (in the comments) of breaking out the
# list items via index: food1 = myList[0]
# also can work.
# food1, food2, food3 = 3_mineral_string.split()
# we can do this if the food string is
# separated by spaces instead.
return D[food1] & D[food2] & D[food3]
用你的食物样本来称呼这个:
food_intersection('copper_magnesium_phosphorus', D)
收益率:
{'Onions'}
在上面的函数中,&
操作符告诉Python调用集合上的.intersection()
方法
由于D[food*]
为我们输入的每种食物返回一个集合,因此我们只需使用&
操作符对所有集合进行排序,或只保留每个集合中存在的值
幸运的是,Python允许我们将所有这些链接在一行上。非常感谢大家的输入。在我的例子中,函数将3种矿物作为一个字符串。然后将字符串解析为一个列表。同样,函数(3_mineral_string,D)随后被转换为包含矿物[“铜”、“镁”、“磷”]的列表。因此,我想我应该首先为每个项目创建3个单独的列表,然后使用intersect?也可以执行l1=myList[0]l2=myList[1]l3=myList[2],D[l1]&D[l2]&D[l3]?对吗?让我知道额外的澄清帮助。如果是,请随时接受答案。
{'Onions'}