2016-11-25 63 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正在尋找的確切解決方案,但我認爲它可能有幫助;)