我有这样的映射关键字.
categories_mapping = {
'comics': 'Comic Books',
'cartoons': 'Comic Books',
'manga': 'Comic Books',
'video and computer games': 'Video Games',
'role playing games': 'Video Games',
'immigration': 'Immigration',
'police': 'Police',
'environmental': 'Environment',
'celebrity fan and gossip': 'Celebrity',
'space and technology': 'NASA / Space',
'movies and tv': 'TV and Movies',
'elections': 'Elections',
'referendums': 'Elections',
'sex': 'Sex',
'music': 'Music',
'technology and computing': 'Technology'}
Run Code Online (Sandbox Code Playgroud)
和这样的清单.
labels = ['technology and computing', 'arts and technology']
Run Code Online (Sandbox Code Playgroud)
如果列表中的任何单词位于字典的键中,我想返回字典的值.
这就是我想出来的,但我认为这不是非常pythonic.
cats = []
for k,v in categories_mapping.items():
for l in labels:
if k in l:
cats.append(v)
return cats
Run Code Online (Sandbox Code Playgroud)
我想要的结果是 ['Technology']
有没有更好的方法呢?
您可以使用intersection标签和字典键:
cats = [categories_mapping[key] for key in set(labels).intersection(categories_mapping)]
Run Code Online (Sandbox Code Playgroud)
部分匹配更新:
cats = [categories_mapping[key] for key in categories_mapping if any(label.lower() in key.lower() for label in labels)]
Run Code Online (Sandbox Code Playgroud)