2017-03-06 27 views
0

我已經預先定義字符串列表的字典「觸發字符串」列表輸出一個新標記字典字典觸發:使用Python從列表的列表

triggers = {'academic': ['studied at', 'studies at', 'studies', 'studies at'], 
    'age': ['years old','months old'], 
    'gender': ['male', 'female'], 
    'pets': ['dog','cat'], 
    'location': ['Lived in','Lives in']} 

,我有一個先前未知分組的信息數據的列表,例如列表:

example_list_of_list = [['Former Teacher of math at'], 
['Studies programming at', 'Stackoverflow'], 
['Lives in','Chicago'], 
['owns','dog', 'cat'] 

欲使用匹配預先定義的鍵值爲每個匹配列表元素附加到一個新的字典,如:

{'academic': ['Former Teacher of math at'], 
'age': None, # np.nan or [] 
'gender': None, # np.nan or [] 
'pets': ['owns','dog','cat'] 
'location': ['Lives in','Chicago'] 
} 

謝謝!

回答

1

你可以很容易地做到這一點使用語義集,我想:

result = {} 
for input in example_list_of_list: 
    for key, triggerset in triggers.items(): 
     if not input.isdisjoint(triggerset): 
      result[key] = result.get(key,[]).append(input) 

但要注意兩件事情:

  • triggers應該是的setdict不是list秒。
  • example_list_of_lists應該是一個的setlistš代替
  • resultlistdict A S的list是因爲多於一個的輸入可能匹配
+0

'LEN(triggers.values()),LEN(觸發器.keys())'是(10,10),輸入是長度4(四組)。但我仍然得到'ValueError:當我嘗試'鍵時觸發器的觸發器數量太多,無法解包':' – EduGord

+0

oops!忘了調用'.items()'。編輯。 – pjz

+0

奇怪的是,這實際上適用於我給出的示例數據,但對於我所擁有的實際數據,它將返回一個空的'dict',所以它不起作用,因爲我確切知道哪些元素應該匹配。我現在太困了,但我肯定會在稍後檢查一下修復程序!謝謝! – EduGord