2016-11-25 107 views
-2

的返回键,如果我有一个单词列表:的Python:字典

list_of_words = ['great','debate','stronger'] 

和字典:

dictionary = {'candidate1':['corruption','election'],'candidate2': ['lady','draintheswamp','stronger','debate'],'candidate3':['healthcare','oil']} 

我要创建检测单词列表的制作功能。

在上面的例子:“候选设备Candidate2”是list_of_words

请不要输入任何模块的最有可能的生产商。效率不是这里主要关心的问题。

+0

为什么你不能导入任何模块? –

回答

0

只需遍历字典项并检查是否有任何项目在给定键的值内,如果是,则附加在列表cand中,该列表包含条件成立的候选项。

然后,如果列表的长度为1,则返回第一个候选人,如果不是,则返回None

在代码中,这看起来是这样的:

def find_candidate(): 
    cand = [] 
    for i,j in dictionary.items(): 
     if any(v in j for v in list_of_words): 
      cand.append(i) 
    return cand[0] if len(cand) == 1 else None 

和调用时,它返回候选2:

find_candidate() 
'candidate2' 

另外,列表创建可与理解来实现:

def find_candidate(): 
    c = [k for k, j in dictionary.items() if any(v in j for v in list_of_words)] 
    return c[0] if len(c) == 1 else None 
+1

OP的问题:给定list_of_words = ['a','b','c']和字典= {'candidate1':['a','b'],'candidate2':['a' ]}是否应该返回'候选1'?如果是这样,这个解决方案将无法工作。 – JesusAlvSoto

0

看到这个问题的本质,我认为这可能是有用的知道数量坦率ates使用列表中的每个单词。这是我会怎么处理它:

def get_candidate(list_of_words, candidates): 
    stats={} 
    for word in list_of_words: 
     stats[word] = [] 
     for candidate, candidate_words in candidates.items(): 
      if word in candidate_words: 
       stats[word].append(candidate) 

    return stats 

list_of_words=['a','b','c','d'] 
candidates={'candidate1':['a','b','c'], 'candidate2':['b','c'], 'candidate3':['c','d']} 

print(get_candidate(list_of_words, candidates)) 

这会打印出:

{ 
'a': ['candidate1'], 
'c': ['candidate3', 'candidate2', 'candidate1'], 
'b': ['candidate2', 'candidate1'], 
'd': ['candidate3'] 
} 

在这里我们可以看到,candidate1是使用单词“a”和candidate3唯一一个使用的唯一一个'D'。 这可能不是OP正在寻找的确切解决方案,但我认为它可能有帮助;)