检查列表项是否包含另一个列表中的项 [英] Check if list item contains items from another list

查看:78
本文介绍了检查列表项是否包含另一个列表中的项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456', 'def-111', 'qwe-111']

bad = ['abc', 'def']

,并要搜索包含字符串"abc"和"def"(以及其他错误的字符串)的项目.我该怎么办?

and want to search for items that contain the string 'abc' and 'def' (and others in bad). How can I do that?

几乎相同的问题此处.

推荐答案

如果只想测试,请将目标列表连接到字符串中,然后像下面这样测试bad的每个元素:

If you just want a test, join the target list into a string and test each element of bad like so:

>>> my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456', 'def-111', 'qwe-111']
>>> bad = ['abc', 'def']
>>> [e for e in bad if e in '\n'.join(my_list)]
['abc', 'def']

从您的问题中,您可以将每个元素作为子字符串相对于另一个元素的子字符串进行测试:

From your question, you can test each element as a sub string against the each element of the other this way:

>>> [i for e in bad for i in my_list if e in i]
['abc-123', 'abc-456', 'def-456', 'def-111']

速度快(与其他方法之一相比):

It is fast (in comparison to one of the other methods):

>>> def f1():
...    [item for item in my_list if any(x in item for x in bad)]
... 
>>> def f2():
...    [i for e in bad for i in my_list if e in i]
... 
>>> timeit.Timer(f1).timeit()
5.062238931655884
>>> timeit.Timer(f2).timeit()
1.35371994972229

根据您的评论,这是如何获取不匹配的元素的方法:

From your comment, here is how you get the elements that do not match:

>>> set(my_list)-{i for e in bad for i in my_list if e in i}
{'ghi-789', 'qwe-111'}

这篇关于检查列表项是否包含另一个列表中的项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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