如果我的帖子使用了错误的线程,我事先表示歉意。
我似乎对尝试使用的这个标记“系统”感到困惑,或者由于我的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)
有人可以分享一些见解吗?
答案 0 :(得分:0)
如果要查找完全匹配的内容,则应检查all
,而不是any
。实际上,您正在尝试检查一个集合是否是另一个集合的子集-您可以从Python的built-in set
type中受益:
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)