簡體   English   中英

從包含在另一個列表中的列表中查找元素

[英]Finding elements from a list included in another one

我有兩個清單

list_1=['mom','father','daughter','dog','soccer']
list_2=['beautiful mom','father day','snoop dog','Manchester United','Windows Office', 'Snoopy Dog']

並且我想構建一個關系,無論list_1中的單詞是否在list_2 例如:

mom : ['beautiful mom']
father : ['father day']
daughter : []
dog : ['snoop dog', 'Snoopy Dog']
soccer : [] 

對於list_1每個元素,我需要查看list_2 如果包含該元素,我會將其添加到列表中。 我試過如下:

set(list_1).issubset(list_2)

查看子集; 但正如我所提到的,我的預期輸出將是這樣的(在熊貓數據框中):

list_1         Match
mom        ['beautiful mom']
father     ['father day']
daughter   []
dog        ['snoop dog', 'Snoopy Dog']
soccer     [] 

您可以創建一個倒排索引,將單個單詞映射到list_2短語。 然后只需從list_1中查找它們即可:

from collections import defaultdict

list_1=['mom','father','daughter','dog','soccer']
list_2=['beautiful mom','father day','snoop dog','Manchester United','Windows Office', 'Snoopy Dog']

index = defaultdict(list)

for v in list_2:
    for k in v.split():
        index[k.lower()].append(v)

res = {k:index[k.lower()] for k in list_1}

res將是:

{'mom': ['beautiful mom'],
 'father': ['father day'],
 'daughter': [],
 'dog': ['snoop dog', 'Snoopy Dog'],
 'soccer': []}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM