[英]Python using dict of “triggers strings” lists to output a new labeled dict from a list of lists
我已经预定义了字符串触发器列表的字典:
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']
}
谢谢!
我认为,使用集合语义可以最轻松地做到这一点:
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
应该是一个dict
的set
不是list
秒。 example_list_of_lists
应该是set
的list
result
是list
的list
的dict
,因为可能有多个输入匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.