首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >匹配字典和列表(Python)

匹配字典和列表(Python)
EN

Stack Overflow用户
提问于 2016-08-08 15:47:25
回答 4查看 398关注 0票数 1

我有一本分类词词典。如果单词与我的列表中的单词匹配,我想输出这些类别。目前,我的代码就是这样的:

代码语言:javascript
复制
dictionary = {
    "object" : 'hat',
    "animal" : 'cat',
    "human" : 'steve'
}

list_of_things = ["steve", "tom", "cat"]

for categories,things in dictionary.iteritems():
    for stuff in list_of_things:

        if stuff in things:
            print categories
        if stuff not in things:
            print "dump as usual"

当前的输出如下:

代码语言:javascript
复制
dump as usual
dump as usual
dump as usual
human
dump as usual
dump as usual
dump as usual
dump as usual
animal

但我希望输出如下所示:

代码语言:javascript
复制
human
dump as usual 
animal

我不想让我的列表在字典里把它遍历的所有内容都打印出来。我只想把它打印出来。我该怎么做?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-08-08 17:01:01

首先,您的字典结构很差;它似乎交换了它的键和值。通过使用类别作为键,每个类别只能有一个对象,这可能不是您想要的。这也意味着你必须阅读字典中的每一个条目,才能查找一个条目,这通常是一个坏兆头。解决这个问题的方法很简单:将项目放在冒号的左边,类别放在右边。然后,您可以使用“in”操作符轻松地搜索字典。

至于您直接问的问题,您应该首先遍历list_of_things,根据字典检查每一个,然后打印结果。这将准确地打印列表中每一项的内容。

代码语言:javascript
复制
dictionary = {
    'hat' : 'object',
    'cat' : 'animal',
    'steve' : 'human'
}

list_of_things = ['steve', 'tom', 'cat']

for thing in list_of_things:
    if thing in dictionary:
        print dictionary[thing]
    else:
        print "dump as usual"

这一产出如下:

代码语言:javascript
复制
human
dump as usual
animal
票数 1
EN

Stack Overflow用户

发布于 2016-08-08 15:50:49

您可以在内部for循环中使用布尔值,从False (未找到类别)更改为True (找到了类别),然后只在for循环if boolean = False:的末尾打印if boolean = False:

代码语言:javascript
复制
isMatchFound = False
for categories, things in dictionary.iteritems():
    isMatchFound = False
    for stuff in list_of_things:
        if stuff in things:
            isMatchFound = True
            print stuff
    if isMatchFound == False:
        print("dump as usual")
票数 1
EN

Stack Overflow用户

发布于 2016-08-08 15:55:47

根据实际数据与示例的相似程度,您可以执行以下操作:

代码语言:javascript
复制
category_thing= {
    "object" : 'hat',
    "animal" : 'cat',
    "human" : 'steve'
}

list_of_things = ["steve", "tom", "cat"]
thingset=set(list_of_things) # just for speedup

for category,thing in category_thing.iteritems():

        if thing in thingset:
            print category
        else:
            print "dump as usual"

或者,如果您的映射真的像在您的示例中那样简单,那么您可以这样做。

代码语言:javascript
复制
category_thing= {
    "object" : 'hat',
    "animal" : 'cat',
    "human" : 'steve'
}

thing_category=dict((t,c) for c,t in category_thing.items()) # reverse the dict - if you have duplicate values (things), you should not do this

list_of_things = ["steve", "tom", "cat"]

for stuff in list_of_things:
     msg=thing_category.get(stuff,"dump as usual")
     print msg
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38833527

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档