[英]Given key-value pair(s), derive the item from a dictionary
I apologize in advance if my post is at the wrong thread. 如果我的帖子出错了,我会提前道歉。 I seem to have got myself confused in this tagging 'system' that I am trying to do, that, or the logic has strayed in the use of dictionaries as my
conditions
can have multiple keys/ values... 我似乎对这个标记'系统'感到困惑,我正在努力做到这一点,或者逻辑因使用字典而误入歧途,因为我的
conditions
可能有多个键/值...
At the moment, the results that I am trying to achieve is only possible if I only stick to the use of either and
or or
method but yet I am trying to achieve both, if possible. 目前,我试图实现的结果只有在我坚持使用任何
and
/ or
方法时才有可能,但如果可能的话,我试图实现两者。
#conditions = {'motions': ['walk']}
#conditions = {'motions': ['run']}
conditions = {'motions': ['run', 'walk']}
# 1. if only 'run', item02 and item04 should be shown
# 2. if only 'walk' + 'run', item04 should be shown
my_items = [
{'item01' : {'motions': ['walk']}},
{'item02' : {'motions': ['run']}},
{'item03' : {'motions': ['crawl']}},
{'item04' : {'motions': ['run', 'walk']}},
]
result = []
for m in my_items:
for mk, mv in m.items():
res1 = all(any(x in mv.get(kc, []) for x in vc) for kc, vc in conditions.items())
all_conditions_met = len(conditions) == len(mv) #False
for cond in conditions:
if cond in mv:
res2 = all_conditions_met and (set(mv[cond]) == set(conditions[cond]))
all_conditions_met = bool(res1 and res2)
# # if I use bool(res1 and res2)
# returns me only item02, incorrect for #1
# returns me only item04, correct for #2
# if I use bool(res1 or res2)
# returns me item02 and item04, incorrect for #1
# returns me item01, item02 and item04, incorrect for #2
else:
all_conditions_met = False
break
if all_conditions_met:
result.append(mk)
Could someone kindly share some insights? 有人可以分享一些见解吗?
If you're looking for full matches, then you should check for all
, not any
. 如果你正在寻找完整的比赛,那么你应该检查
all
,而不是any
。 In fact, you are trying to check whether a set is a subset of another one -- and you can benefit from Python's built-in set
type : 实际上,您正在尝试检查集合是否是另一个集合的子集 - 您可以从Python的内置
set
类型中受益:
names = []
for row in my_items:
for name, subconditions in row.items():
full_match = all(
set(conditions[key]) <= set(subconditions.get(key, []))
for key in conditions.keys()
)
if full_match:
names.append(name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.