combine if filter terms from list
MRAB
python at mrabarnett.plus.com
Fri Apr 21 20:59:56 EDT 2017
On 2017-04-22 01:17, Rory Schramm wrote:
> Hi,
>
> I'm trying to use python list comprehensions to combine multiple terms for
> use by a for loop if condition.
>
>
> filters = [ 'one', 'two', 'three']
> for line in other_list:
> if ' and '.join([item for item in filters]) not in line[2]:
> print line
>
> The list comp returns one and two and three and ..
>
> The problem I'm having is the for loop isn't filtering out the terms from
> the filter list. I suspect the problem is the if condition is treating the
> results for the list comprehension as a literal string and not part of the
> if condition itself. I'm not sure how to fix this though.
>
Correct. The join is returning 'one and two and three'. The condition is
true if that string isn't in line[2]. (What is line? Is it a string? If
so, then line[2] is one character of that string.)
> Any ideas on How to make this work?
>
If you want it to do this:
if 'one' not in line[2] and 'two' not in line[2] and 'three' not in
line[2]:
you can write:
if all(word not in line[2] for word in filters):
or:
if not any(word in line[2] for word in filters):
More information about the Python-list
mailing list