[英]Pythonic way to check if element in a list contains in key dictionary
我有一個這樣的映射關鍵字。
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'}
和這樣的清單。
labels = ['technology and computing', 'arts and technology']
如果列表中的任何單詞在字典的鍵中,我想返回字典的值。
這是我想出的,但是我認為這不是很pythonic。
cats = []
for k,v in categories_mapping.items():
for l in labels:
if k in l:
cats.append(v)
return cats
我想要的結果是['Technology']
有更好的方法嗎?
您可以使用標簽和字典鍵的intersection
:
cats = [categories_mapping[key] for key in set(labels).intersection(categories_mapping)]
更新部分匹配:
cats = [categories_mapping[key] for key in categories_mapping if any(label.lower() in key.lower() for label in labels)]
>>> [categories_mapping[l] for l in labels if l in categories_mapping]
['Technology']
您可以擺脫外部循環:
for l in labels:
if l in categories_mapping:
cats.append(categories_mapping[l])
或作為列表組合:
cats = [v for k, v in categories_mapping if k in l]
>>> 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'}
>>> labels = ['technology and computing', 'arts and technology']
>>> cats = []
>>> for l in labels:
if l in categories_mapping:
cats.append(categories_mapping[l])
>>> cats
['Technology']
cats = [v for k, v in categories_mapping.items() if k in labels]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.