diff lists
Ken Seehof
kens at sightreader.com
Wed Mar 28 12:56:53 EST 2001
It's often a good idea to use dictionaries instead of lists for
this kind of thing if performance is important. A dictionary
is a better model for a set than a list is, although this may seem
intuitively strange at first. People should use dictionaries more;
they are very powerful, and not just for lookup tables.
I am assuming your lists won't have duplicates (e.g. ['a','b','b'])
since you seem to be interested in set operations.
Try this:
>>> def andnot(a, b):
... d = {}
... for x in a:
... d[x]=0 # value doesn't matter, we're just using the key
... for x in b:
... if d.has_key(x):
... del d[x]
... return d.keys()
...
>>> a = ['a', 'b', 'c', 'd', 'e', 'f']
>>> b = ['e', 'c', 'f']
>>> andnot(a,b)
['d', 'b', 'a']
This will be super fast (linear time) even for really big lists.
Note that if b is small compared to a, you are significantly
better off using dictionaries in the first place rather than
translating as in the above example.
This one uses dictionaries instead of lists:
>>> def andnot2(a, b):
... d = a.copy()
... for x in b.keys():
... if d.has_key(x):
... del d[x]
... return d
...
>>> a = {'a':0, 'b':0, 'c':0}
>>> b = {'b':0}
>>> andnot2(a,b)
{'c': 0, 'a': 0}
----- Original Message -----
From: "Oliver Vecernik" <vecernik at aon.at>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Wednesday, March 28, 2001 4:47 AM
Subject: diff lists
> Hi,
>
> I've got following two lists:
>
> ['a', 'b', 'c', 'd', 'e', 'f']
> ['e', 'c', 'f']
>
> I'd like to have the result:
>
> ['a', 'b', 'd']
>
> The list need not to be ordered. ['d', 'a', 'b'] will also be ok. What
> is the most effective way to achive that result?
>
> Oliver
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list