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


Groups > comp.lang.python > #11579 > unrolled thread

Re: testing if a list contains a sublist

Started byMRAB <python@mrabarnett.plus.com>
First post2011-08-16 17:41 +0100
Last post2011-08-16 17:41 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: testing if a list contains a sublist MRAB <python@mrabarnett.plus.com> - 2011-08-16 17:41 +0100

#11579 — Re: testing if a list contains a sublist

FromMRAB <python@mrabarnett.plus.com>
Date2011-08-16 17:41 +0100
SubjectRe: testing if a list contains a sublist
Message-ID<mailman.83.1313512923.27778.python-list@python.org>
On 16/08/2011 00:26, Johannes 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.
>
Here's my solution, using the Counter class:

 >>> from collections import Counter
 >>>
 >>> c1 = Counter([1,2])
 >>> c2 = Counter([1,2,3,4,5])
 >>> (c1 & c2) == c1
True
 >>>
 >>> c1 = Counter([1,2,2,])
 >>> c2 = Counter([1,2,3,4,5])
 >>> (c1 & c2) == c1
False
 >>>
 >>> c1 = Counter([1,2,3])
 >>> c2 = Counter([1,3,5,7])
 >>> (c1 & c2) == c1
False

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web