给定键值对,从字典派生项

2024-05-15 12:52:56 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我的帖子发错了,我提前道歉。 我似乎把自己搞糊涂了,在这个标记“系统”中,我正在尝试这样做,或者逻辑在使用字典时出现了偏差,因为我的conditions可以有多个键/值

目前,如果我只坚持使用andor方法的话,我试图实现的结果是可能的,但是如果可能的话,我正在尝试实现这两种方法

#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)

有人能分享一些见解吗


Tags: andruninonlyforifitemsall
1条回答
网友
1楼 · 发布于 2024-05-15 12:52:56

如果要查找完全匹配,那么应该检查all,而不是any。实际上,您正在尝试检查一个集合是否是另一个集合的子集,并且可以从Python的built-in ^{} 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)

相关问题 更多 >