Reputation: 103
I have a list of strings and currently I can search for one substring at the time:
str = ['abc', 'efg', 'xyz']
[s for s in str if "a" in s]
which correctly returns
['abc']
Now let's say I have a list of substrings instead:
subs = ['a', 'ef']
I want a command like
[s for s in str if anyof(subs) in s]
which should return
['abc', 'efg']
Upvotes: 2
Views: 129
Reputation: 39406
I still like map
and filter
, despite what is being said against and how comprehension can always replace a map
and a filter
. Hence, here is a map + filter + lambda
version:
print filter(lambda x: any(map(x.__contains__,subs)), s)
which reads:
filter elements of s that contain any element from subs
I like how this uses words that carry a strong semantic meaning, rather than only if, for, in
Upvotes: 0
Reputation: 80657
Simply use them one after the other:
[s for s in str for r in subs if r in s]
>>> r = ['abc', 'efg', 'xyz']
>>> s = ['a', 'ef']
>>> [t for t in r for x in s if x in t]
['abc', 'efg']
Upvotes: 0
Reputation: 78780
>>> s = ['abc', 'efg', 'xyz']
>>> subs = ['a', 'ef']
>>> [x for x in s if any(sub in x for sub in subs)]
['abc', 'efg']
Don't use str
as a variable name, it's a builtin.
Upvotes: 2
Reputation: 2356
Gets a little convoluted but you could do
[s for s in str if any([sub for sub in subs if sub in s])]
Upvotes: 0