26

我有一个清单:

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

bad = ['abc', 'def']

并且想要搜索包含字符串“abc”和“def”(以及其他错误)的项目。我怎样才能做到这一点?

这里几乎相同的问题。

4

4 回答 4

42

如果您只是想要一个测试,请将目标列表加入一个字符串并测试每个元素,bad如下所示:

>>> 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']

根据您的问题,您可以通过以下方式将每个元素作为子字符串与另一个元素的每个元素进行测试:

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

它很快(与其他方法之一相比):

>>> 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

根据您的评论,您可以通过以下方式获取不匹配的元素:

>>> set(my_list)-{i for e in bad for i in my_list if e in i}
{'ghi-789', 'qwe-111'}
于 2012-07-04T12:52:29.277 回答
13
In [4]: filter(lambda item: any(x in item for x in bad), my_list)
Out[4]: ['abc-123', 'def-456', 'abc-456', 'def-111']

或者

In [13]: [item for item in my_list if any(x in item for x in bad)]
Out[13]: ['abc-123', 'def-456', 'abc-456', 'def-111']
于 2012-07-04T12:44:07.573 回答
2
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
bad = ['abc', 'def']
for s in some_list:
    for item in bad:
       if item in s:
          print 'Found ', s

这很简单,工作正常且快速(仅当您的列表不是很大时。)

于 2012-07-04T12:38:32.863 回答
0
some_list=['abc-123', 'def-456', 'ghi-789', 'abc-456']
bad = ['abc', 'def']
for i in range (0,len(bad)):
    if bad[i] in some_list:
        print('Found a bad entry:', bad[i])
于 2016-10-17T13:32:47.563 回答