如果我的帖子发错了,我提前道歉。
我似乎把自己搞糊涂了,在这个标记“系统”中,我正在尝试这样做,或者逻辑在使用字典时出现了偏差,因为我的conditions
可以有多个键/值
目前,如果我只坚持使用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)
有人能分享一些见解吗
如果要查找完全匹配,那么应该检查} type 中获益:
all
,而不是any
。实际上,您正在尝试检查一个集合是否是另一个集合的子集,并且可以从Python的built-in ^{相关问题 更多 >
编程相关推荐