[英]Compare two list of list in python
我有兩個清單
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']
附加到一個新列表中。
這是您的解決方案:
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]])
PS:你很困惑地提出了這個問題,“大於或等於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']]
如果您想避免嵌套,請將邏輯分解為一個函數以減少嵌套。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.