Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #11921

Re: testing if a list contains a sublist

References <4E49AB3E.9000801@web.de>
Date 2011-08-20 09:06 -0700
Subject Re: testing if a list contains a sublist
From Simon Forman <sajmikins@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.267.1313856408.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Aug 15, 2011 at 4:26 PM, Johannes <dajo.mail@web.de> wrote:
> hi list,
> what is the best way to check if a given list (lets call it l1) is
> totally contained in a second list (l2)?
>
> for example:
> l1 = [1,2], l2 = [1,2,3,4,5] -> l1 is contained in l2
> l1 = [1,2,2,], l2 = [1,2,3,4,5] -> l1 is not contained in l2
> l1 = [1,2,3], l2 = [1,3,5,7] -> l1 is not contained in l2
>
> my problem is the second example, which makes it impossible to work with
> sets insteads of lists. But something like set.issubset for lists would
> be nice.
>
> greatz Johannes
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Probably not the most efficient way, but I wanted to mention it:


from difflib import SequenceMatcher


def list_in(a, b):
    '''Is a completely contained in b?'''
    matcher = SequenceMatcher(a=a, b=b)
    m = matcher.find_longest_match(0, len(a), 0, len(b))
    return m.size == len(a)


Cheers,
~Simon

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: testing if a list contains a sublist Simon Forman <sajmikins@gmail.com> - 2011-08-20 09:06 -0700

csiph-web