Python使用dict of“triggers strings”列表从列表中输出一个新的带标签的dict

2024-03-28 21:17:44 发布

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

我已经预先定义了一个字符串触发器列表:

triggers = {'academic': ['studied at', 'studies at', 'studies', 'studies at'],
     'age': ['years old','months old'],
     'gender': ['male', 'female'],
     'pets': ['dog','cat'],
     'location': ['Lived in','Lives in']}

我有一个以前不知道的分组信息数据列表,例如:

example_list_of_list = [['Former Teacher of math at'],
 ['Studies programming at', 'Stackoverflow'],
 ['Lives in','Chicago'],
 ['owns','dog', 'cat']

我想使用匹配预定义键值将每个匹配列表元素附加到新字典中,例如:

{'academic': ['Former Teacher of math at'],
'age': None, # np.nan or []
'gender': None, # np.nan or []
'pets': ['owns','dog','cat']
'location': ['Lives in','Chicago']
 }

谢谢!你知道吗


Tags: ofin列表agelocationgenderoldat
1条回答
网友
1楼 · 发布于 2024-03-28 21:17:44

我认为,使用集合语义最容易做到这一点:

result = {}
for input in example_list_of_list:
    for key, triggerset in triggers.items():
        if not input.isdisjoint(triggerset):
            result[key] = result.get(key,[]).append(input)

但请注意以下几点:

  • triggers应该是setdict而不是list
  • example_list_of_lists应该是listset
  • resultlistdict,因为可能有多个输入匹配

相关问题 更多 >