ordered sets operations on lists..
Raymond Hettinger
python at rcn.com
Fri Feb 10 14:30:35 EST 2006
[Amit Khemka]
> > Hello, Is there a *direct* way of doing set operations on lists which
> > preserve the order of the input lists ?
> > For Ex. l1 = [1, 5, 3, 2, 4, 7]
> > l2 = [3, 5, 10]
> >
> > and (l1 intersect l2) returns [5, 3] .... (and (l2 intersect l1)
[bonono]
> what do you mean by "direct" way ? ugly(some said) one liner ?
>
> filter(set(l1).intersection(set(l2)).__contains__, l1)
> filter(set(l1).intersection(set(l2)).__contains__, l2)
The intersection step is unnecessary, so the answer can be simplified a
bit:
>>> filter(set(l2).__contains__, l1)
[5, 3]
>>> filter(set(l1).__contains__, l2)
[3, 5]
More information about the Python-list
mailing list