[Tutor] Comparing two lists

Vince Spicer vince at vinces.ca
Thu Sep 16 20:59:08 CEST 2010


On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer <vince at vinces.ca> wrote:

>
>
> On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe <michael at trollope.org>wrote:
>
>> Hello,
>>
>> I have two lists.
>>
>> alist = ['label', 'guid']
>>
>> blist = ['column0label', 'column1label', 'dimension0guid',
>> 'description', 'columnid']
>>
>> I want to iterate over blist and extract the items that match my
>> substrings in alist; alternatively, throw out the items that aren't in
>> alist (but, I've had bad experiences removing items from lists "in
>> place," so I tend toward the "copy" motif.)
>>
>> In real life, blist column entries could have embedded column numbers
>> from 0 to 19.
>>
>> I can do this with excrutiatingly painful 'for' loops.  Looking for
>> something more efficient and elegant.
>>
>> Thanks.
>>
>> mp
>>
>> --
>> Michael Powe            michael at trollope.org            Naugatuck CT USA
>>
>> "The secret to strong security: less reliance on secrets."
>> -- Whitfield Diffie
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> Michel,
>
> One solution is to use list comprehensions.
>
> newlist = [x for x in blist if [a for a in alist if a in x]]
>
> This works, although there may be more efficient ways to accomplish this
>
> Vince
>
>
On major speed up is to make a simple filter that returns as soon as a match
is found instead of
completing the loop every element in alist

def filter_(x, against):
    for a in against:
        if a in x:
            return True
    return False

newlist = [x for x in blist if filter_(x, alist)]

:)

Vince
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/11a6cd59/attachment.html>


More information about the Tutor mailing list