What is the most efficient way to compare similar contents in two lists?

Zachary Dziura zcdziura at gmail.com
Mon Jun 13 11:21:29 EDT 2011


On Jun 13, 11:09 am, Chris Angelico <ros... at gmail.com> wrote:
> On Tue, Jun 14, 2011 at 12:58 AM, Zachary Dziura <zcdzi... at gmail.com> wrote:
> > if set(source_headers) == set(target_headers):
> >    similar_headers = len(source_headers)
>
> Since you're making sets already, I'd recommend using set operations -
> same_headers is the (length of the) intersection of those two sets,
> and different_headers is the XOR.
>
> # If you need the lists afterwards, use different variable names
> source_headers = set(source_headers)
> target_headers = set(target_headers)
> similar_headers = len(source_headers & target_headers)
> different_headers = len(source_headers ^ target_headers)
>
> Chris Angelico

Wow! That was a lot easier than I thought it would be! I guess I
should have done a little bit more research into such operations.
Thanks a bunch!!



More information about the Python-list mailing list