如果你只是想进行测试,将目标列表连接成字符串,并像下面这样测试
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'}