filter a list of strings

Peter Otten __peter__ at web.de
Thu Dec 3 05:13:57 EST 2015


Laura Creighton wrote:

> In a message of Thu, 03 Dec 2015 10:27:19 +0100, c.buhtz at posteo.jp writes:
>>Thank you for your suggestion. This will help a lot.
>>
>>On 2015-12-03 08:32 Jussi Piitulainen <harvesting at is.invalid> wrote:
>>> list = [ item for item in list
>>>          if ( 'Banana' not in item and
>>>               'Car' not in item ) ]
>>
>>I often saw constructions like this
>>  x for x in y if ...
>>But I don't understand that combination of the Python keywords (for,
>>in, if) I allready know. It is to complex to imagine what there really
>>happen.
>>
>>I understand this
>>  for x in y:
>>    if ...
>>
>>But what is about the 'x' in front of all that?
> 
> This is a list comprehension.
> see:
> https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
> 
> But I would solve your problem like this:
> 
> things_I_do_not_want = ['Car', 'Banana', <add all of them here>]
> things_I_want = []
> 
> for item in list_of_everything_I_started_with:
>     if item not in things_I_do_not_want:
>        things_I_want.append(item)

Note that unlike the original code your variant will not reject
"Blue Banana". If the OP wants to preserve the '"Banana" in item' test he 
can use

for item in list_of_everything_I_started_with:
    for unwanted in things_I_do_not_want:
        if unwanted in item:
            break
    else: # executed unless the for loop exits with break
        things_I_want.append(item)

or

things_I_want = [
    item for item in list_of_everything_I_started_with
    if not any(unwanted in item for unwanted in things_I_do_not_want)
]




More information about the Python-list mailing list