2017-10-07 251 views
-1

列表的兩個列表我有兩個列表比較蟒蛇

lst1=[['hey','jude' ,'fox'],['how','you','do']] 
lst2=[['hey','paul'],['how','do']] 

我想每個列表中LST1與LST2每個列表進行比較。如果它們的常用單詞大於或等於1.那麼我需要將更大的列表追加到新列表中。如果他們有共同的詞< 1那麼我需要將這兩個列表追加到同一個新列表。
例如:['hey', 'jude','fox']['hey','paul']進行比較,因爲它們具有重複一次的常用單詞hey。我需要將更大的列表['hey', 'jude','fox']添加到新列表中。

+0

請顯示所需的輸出。 –

+0

你有什麼嘗試?請參閱[如何創建最小,完整和可驗證示例](https://stackoverflow.com/help/mcve) –

回答

0

這裏是您的解決方案:

lst1=[['hey','jude' ,'fox'],['how','you','do']] 
lst2=[['hey','paul'],['how','do']] 
    new_list=[] 

    for item in lst1: 
     for item_1 in lst2: 
      if isinstance(item_1,list): 
       for sub_item in item_1: 
        if sub_item in item: 
         if len(sub_item)>=1: 
          if len(item)>len(item_1): 
           if item not in new_list: 
            new_list.append(item) 
          elif len(item_1)>len(item): 
           if item_1 not in new_list: 
            new_list.append(item_1) 


         if len(sub_item)<2: 
          if sub_item not in new_list: 
           new_list.append(sub_item) 
           new_list.append(item) 



    print([j for i,j in enumerate(new_list) if j not in new_list[:i]]) 

P.S:你說有困惑的問題,你是什麼 「字樣大於或等於1」的意思你是指單詞的長度還是單詞的匹配?我接受了這個單詞。

測試:

與你的列表:

輸出:

[['hey', 'jude', 'fox'], ['how', 'you', 'do']] 

當列表中的一個有comman小於2 LEN信然:

lst1=[['hey','jude' ,'fox'],['how','you','do'],["wow"],["wllla","wlahi","aasma"],["h","i","j"]] 
lst2=[['hey','paul'],['how','do'],["wllla"],["h"]] 

輸出:

[['hey', 'jude', 'fox'], ['how', 'you', 'do'], ['wllla', 'wlahi', 'aasma'], ['h', 'i', 'j'], 'h'] 

當第二個列表具有最大公共列表的話它的匹配情況:

lst1=[['hey','jude' ,'fox'],['how','you','do'],["wow"],["wllla","wlahi","aasma"],["h","i","j"],["abc","def"]] 
lst2=[['hey','paul'],['how','do'],["wllla"],["h"],["abc","def","ghi"]] 

輸出:

[['hey', 'jude', 'fox'], ['how', 'you', 'do'], ['wllla', 'wlahi', 'aasma'], ['h', 'i', 'j'], 'h', ['abc', 'def', 'ghi']] 
如果你想避免嵌套打破邏輯

出功能 減少嵌套。