I have datalist and filterlist and I want to use list comprehension method to search any item in datalist which its string contains any word from the filterlist:
>>> datalist=['mytest123orange','dark angle','double69','spartan','broken image 999','2 cup of tea']
>>> filterlist=['test','2','x','123','orange']
>>> print [i for i in datalist if len([ j for j in filterlist if j in i])>0 ]
['test123orange', '2 cup of tea']
It's working as i want. But the problem is that to get the value from len([ j for j in filterlist if j in i ])>0
, it will need to loop all the item inside the filterlist. So even if it match the first item in filterlist, the loop will have to go through till the end. For example when
try to check the 'mytest123orannge'
, if the test in filterlist already match it then it's enough, I want to 'break' the loop so I don't want to loop for the rest. So I don't need to match for 'orange'
or '2'
or '123'
.
My questions :
- How can I break inside that loop?
- Is there any other better method?