Test if list contains another list
J. Cliff Dyer
jcd at sdf.lonestar.org
Tue Sep 9 12:09:24 EDT 2008
On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote:
> Matimus a écrit :
> > On Sep 8, 12:32 am, Bruno Desthuilliers
> > <bdesth.quelquech... at free.quelquepart.fr> wrote:
> (snip)
> >> >>> set(a).issubset(set(b))
> >> True
> >> >>>
> >>
> > Just to clarify, doing it using sets is not going to preserve order OR
> > number of elements that are the same.
> >
> > That is:
> >
> >>>> a = [1,1,2,3,4]
> >>>> b = [4,5,3,7,2,6,1]
> >>>> set(a).issubset(set(b))
> > True
> >
> > This will return True if b contains at least on of each element found
> > in a. If the OP wanted to check that list `a` appeared in order
> > somewhere in list `b` then sets won't work.
>
> Indeed, and I should have mentionned this myself. Thanks for this reminder.
>
If preserving order is important, strings have many of the properties
you're looking for, but it might take some work to figure out a suitable
way to convert to a string. The problem is easier if you know something
about the inputs. If all inputs are known to be numbers between 0 and
15, you can just do:
if ''.join(map(hex, a)) in ''.join(map(hex, b)):
return True
Hmm... actually, with the '0x' prefix that hex() puts on numbers, I
think this works for arbitrary integers.
Cheers,
Cliff
More information about the Python-list
mailing list