匹配两个列表之间的相似元素 [英] matching similar elements in between two lists

查看:180
本文介绍了匹配两个列表之间的相似元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,所以很抱歉,这是一个愚蠢的问题.

I'm new to python so apologies if its a silly question.

我有两个列表
L1=['marvel','audi','mercedez','honda']

I have two lists
L1=['marvel','audi','mercedez','honda'] and

L2=['marvel comics','bmw','mercedez benz','audi'].

我想提取包含在list L2中与list L1匹配的匹配元素.所以我做了什么:

I want to extract matching elements which contains in list L2 matched with list L1. So what I done :

for i in L1:
   for j in L2:
       if j in i:
          print (j)

  output is ['audi']

但是,如果元素也包含任何单词匹配,例如mercedez benz中的mercedezmarvel comics中的marvel,我也想返回元素.因此最终输出将是:

But, I also wants to return elements if its also consist any word match like mercedez in mercedez benz and marvel in marvel comics. so final output would be:

j=['audi','mercedez benz','marvel comics']

推荐答案

我认为您真正想要的是L2的元素,其中包含L1中的任何元素.因此,只需将if j in i替换为if i in j:

I think what you really want here is the elements of L2 that contain any elements in L1. So simply replace if j in i with if i in j:

for i in L1:
   for j in L2:
       if i in j:
          print (j)

这将输出:

marvel comics
audi
mercedez benz

这篇关于匹配两个列表之间的相似元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆