best way to compare contents of 2 lists?

Arnaud Delobelle arnodel at googlemail.com
Fri Apr 24 03:08:34 EDT 2009


On Apr 24, 7:12 am, bearophileH... at lycos.com wrote:
[...]
> Another solution is to use frequency dicts, O(n):
>
> from itertools import defaultdict
> d1 = defaultdict(int)
> for el in a:
>     d1[el] += 1
> d2 = defaultdict(int)
> for el in b:
>     d2[el] += 1
> d1 == d2

Thanks to the power of negative numbers, you only need one dict:

d = defaultdict(int)
for x in a:
    d[x] += 1
for x in b:
    d[x] -= 1
# a and b are equal if d[x]==0 for all x in d:
not any(d.itervalues())

--
Arnaud



More information about the Python-list mailing list