我有一本分类词词典。如果单词与我的列表中的单词匹配,我想输出这些类别。目前,我的代码就是这样的:
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"当前的输出如下:
dump as usual
dump as usual
dump as usual
human
dump as usual
dump as usual
dump as usual
dump as usual
animal但我希望输出如下所示:
human
dump as usual
animal我不想让我的列表在字典里把它遍历的所有内容都打印出来。我只想把它打印出来。我该怎么做?
发布于 2016-08-08 17:01:01
首先,您的字典结构很差;它似乎交换了它的键和值。通过使用类别作为键,每个类别只能有一个对象,这可能不是您想要的。这也意味着你必须阅读字典中的每一个条目,才能查找一个条目,这通常是一个坏兆头。解决这个问题的方法很简单:将项目放在冒号的左边,类别放在右边。然后,您可以使用“in”操作符轻松地搜索字典。
至于您直接问的问题,您应该首先遍历list_of_things,根据字典检查每一个,然后打印结果。这将准确地打印列表中每一项的内容。
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"这一产出如下:
human
dump as usual
animal发布于 2016-08-08 15:50:49
您可以在内部for循环中使用布尔值,从False (未找到类别)更改为True (找到了类别),然后只在for循环if boolean = False:的末尾打印if boolean = False:。
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")发布于 2016-08-08 15:55:47
根据实际数据与示例的相似程度,您可以执行以下操作:
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"或者,如果您的映射真的像在您的示例中那样简单,那么您可以这样做。
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 msghttps://stackoverflow.com/questions/38833527
复制相似问题