2017-03-15 54 views
-1

我需要比較兩種列表如下。Python比較元組列表和聚集詞列表

詞語的列表以及它們的頻率列表的

list_1=[('psicomotricita',6), ('psicomotorio',5) , ('psicomotorie',6),('psicomotore', 7), 
     ('bella',1), ('biella',7), ('bello',3),('zorro',4)] 

列表,其中每一個子列表是通過它們的相似性的單詞的聚類。

list_2=[['psicomotricità', 'psicomotorio','psicomotorie','psicomotore'] 
     ['bella', 'biella', 'bello'] 
     ['zorro']] 

所以,我需要循環的list_2的每個子列表,以回升,在與最大頻率LIST_1比較字。

結果應該是:

final_list['psicomotore','biella','zorro'] 

有沒有人誰可以幫我?謝謝!

+0

可能重複[按照相似性和頻率對字符串列表進行聚類](http:/ /stackoverflow.com/questions/42556184/clustering-a-list-of-string-by-their-similarity-and-frequence) –

+0

嘿@ Anony-Mousse,你如何看待下面的答案? – CosimoCD

回答

0

經過漫長的鬥爭(我是Python新手)我解決了上述問題。

所以,首先我轉換的元組的列表字典:

d = {t[0]:int(t[1]) for t in list_1} 

其次,我創建了以下功能:

def SortTuples(list, dict): 
final_ls= [] 
ddd= [] 
for el in list_2: 
    for key, value in d.iteritems(): 
     if key in el: 
      ddd.append((key,value)) 
    z= (max(ddd,key=itemgetter(1))[0]) 
    final_ls.append(z) 
    ddd= [] 
return final_ls 

結果是與他們有單詞的列表最大頻率:

Out: ['psicomotore', 'biella', 'zorro'] 
+0

字典的目的是,你不需要遍歷所有的項目,並比較關鍵字...那麼簡單地使用字典的最大功能呢? –