Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #11685
| From | Ameretat Reith <ameretat.reith@gmail.com> |
|---|---|
| Subject | Re: testing if a list contains a sublist |
| Date | 2011-08-17 18:41 +0430 |
| References | <4E49AB3E.9000801@web.de> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.129.1313590402.27778.python-list@python.org> (permalink) |
[Multipart message — attachments visible in raw view] - view raw
On Se shanbe 25 Mordad 1390 01:26:54 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.
>
> greatz Johannes
Hope best answer is found so far. for easy answer, i prefer to use Python
`==' operator instead of inner loop.
l=[1,2,3,4,5]
s=[1,2,2]
sc=len(s)
for c in xrange(len(l)-sc+1):
if l[c:sc+c] == s:
print ( 'found at {0}'.format(c) )
break
Since sub-lists memory will be garbage collected, there is no problem in
memory usage, but in time needed for constructing new slice, there is.
--
Amir Ghassemi Nasr (Reith)
GPG ID: 371035B4 (http://46.4.214.112/~reith/reith.asc)
GPG Fingerprint: 18E6 CF11 BE80 F541 DC68 B6AF 9373 DE72 3710 35B4
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: testing if a list contains a sublist Ameretat Reith <ameretat.reith@gmail.com> - 2011-08-17 18:41 +0430
csiph-web