2013-04-22 86 views
2

检查任何价值的存在,我的名单像如何在列表中的蟒蛇

l = ['dd','rr','abcde'] 

l2 = ['ddf','fdfd','123'] 

我想要一个功能,如果任何来自l价值的l2存在哪些返回true。

现在可以进行部分匹配了。我的意思是该字符串应该给出l2

编辑:

输出应该是在我的例子虚假

像真应该因为ddddf

+0

什么是您例如预期的输出?另外,你到目前为止尝试过什么? – cyroxx 2013-04-22 12:05:39

+0

这已经在这里回答http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches,是一个很好的解决方案 – user2307241 2013-04-22 12:07:48

+0

@cyroxx输出应该是真的或假的 – user2294401 2013-04-22 12:10:06

回答

5

这将返回匹配返回true True如果来自l的任何值是l2中的任何值的子字符串:

any(l_value in l2_value for l_value in l for l2_value in l2) 
+0

最后一句我的意思是你的函数应该给出真正的输出,因为'dd'在l1中与'ddf'匹配 – user2294401 2013-04-22 12:09:12

+0

然后我的第二个例子就可以工作了。 – 2013-04-22 12:10:25

0
def match(): 
    for e in l: 
     for e2 in l2: 
      if e in e2: 
       return True 
    else: 
     return False 

这将包括部分匹配。

UPDATE: 使用列表理解:

[re.search(x,",".join(l2)) for x in l if re.search(x,",".join(l2)) is not None] and 'True' or 'False' 
+0

平行四边形! – jamylak 2013-04-22 12:22:47