2017-05-14 80 views
1

我是新來編程,我正在做一個文本挖掘任務。我有一個關鍵字作爲標記和值的字典作爲數據庫中標記的出現。如何檢查字典中的值?

dic={'a':48,'b':32,'c':26} 

並且我還有一個令牌列表,並且我試圖用每個令牌的出現創建一個新列表。如果令牌不字典中,追加0

my_list=['a','b','d','c','a'] 


ideal_output=[48,32,0,26,48] 

我原來的代碼是這樣的:

for word in my_list: 
    for k,v in dic.items():   
     if word==k: 
      ideal_output.append(v) 
     else: 
      ideal_output.append('0') 

,但比我預期它會產生更多的整數,我不知道什麼是根本它錯了。我會感謝您的幫助!

電流輸出看起來像這樣

[ '0',48, '0', '0', '0',32, '0', '0', '0',26,「0 」, '0', '0',48, '0']

+1

請編輯信息,並顯示您的電流輸出 – pstatix

+0

可能的複製[搜索陣列報告「沒有發現」,即使它的發現(HTTP://計算器。com/questions/42913798/searching-array-reports-not-found-even-though-its-found-found) – Barmar

回答

1
dic={'a':48,'b':32,'c':26} 
my_list=['a','b','d','c','a'] 


ideal_output=[] 

for key in my_list: 
    if key in dic: 
    value = dic[key] 
    ideal_output.append(value) 
    else: 
    ideal_output.append(0) 

print(ideal_output)  
2
my_list=['a','b','d','c','a'] 
ideal_output = [dic.get(token, 0) for token in my_list] 
+1

我認爲理解更具可讀性 ideal_output = my_list中令牌的ideal_output = dic.get(令牌,0) – MaLiN2223

+0

謝謝你的建議。我改變了它:) – mohammad

-1

嘗試此,爲避免對循環中的第二:

ideal_output=[] 

for element in my_list: 
    if element in dic.keys(): 
    ideal_output.append(dic[element]) 
    else: 
    ideal_output.append(0) 

print(ideal_output) 
0

步驟一步溶液:

這個答案是爲你而設,也適用於其他難以理解代碼的人。對不起,如果它太詳細,但它可能有助於某人。

首先,我們需要遍歷列表,這意味着我們將檢查其中的每個元素。我們將使用作爲循環。這將檢查連續列表中的每個項目,並將其分配給變量i。它將運行所有的代碼下它,當它的完成,將進入到下一個項目,將其分配給我,又說:

for i in my_list: 
    # Here we'll add more code  

現在,我們需要確定這是名爲「我的項目'在字典中。它是目前由循環檢查的元素。

for i in my_list: 
    if i in dic: #This checks if i is in the dictionary 
     ideal_output.append(dic[i]) # dic[i] is the value we want to add to 
     # We use ideal_output.append and the value in the parentheses to add the value 
     # to the list 

現在,我們要添加「0」到列表中,如果我們把在如果語句條件不滿足:

for i in my_list: 

    if i in dic: 
     ideal_input.append(dic[i]) 

    else: 
     ideal_output.append(0) 

print(ideal_output) #This runs when the loop is finished 
0

你可以使用一個collections.defaultdict。在下面的例子中,它會爲每個找不到的鍵返回0。

In [1]: from collections import defaultdict 

In [2]: di = defaultdict(lambda: 0, {'a':48,'b':32,'c':26}) 

In [3]: di['a'] 
Out[3]: 48 

In [4]: di['x'] 
Out[4]: 0 

In [5]: di['p'] 
Out[5]: 0 

但是,既然您似乎正在計算文本中的字母,請看collections.Counter

In [6]: from collections import Counter 

In [7]: c = Counter('This is a text') 

In [8]: c 
Out[8]: 
Counter({' ': 3, 
     'T': 1, 
     'a': 1, 
     'e': 1, 
     'h': 1, 
     'i': 2, 
     's': 2, 
     't': 2, 
     'x': 1})