检查列表中的元素是否包含在键字典中的Pythonic方法

2024-09-27 21:26:18 发布

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

我有一个这样的映射关键字。你知道吗

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']

如果列表中的任何单词在字典的关键字中,我想返回字典的值。你知道吗

这是我想到的,但我认为这不是很Python。你知道吗

cats = []
for k,v in categories_mapping.items():
    for l in labels:
        if k in l:
            cats.append(v)
return cats

我想要的结果是['Technology']

有更好的方法吗?你知道吗


Tags: andinvideo关键字booksmappinggamescategories
3条回答
>>> 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']
>>> [categories_mapping[l] for l in labels if l in categories_mapping]
['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)]

相关问题 更多 >

    热门问题