[Python Glasgow] consecuetive members of a list

Mark Smith mark.smith at practicalpoetry.co.uk
Wed Apr 30 12:31:45 CEST 2014


You're going to love this - it's a trick I learned relatively recently .

Firstly, what you're talking about is n-grams (in this case you want to
generate 2-grams from a list). Secondly, the code is fiddly but short (it's
the one-liner in the n-gram function below):

a = [1, 7, 19, 1110]

def ngram(seq, n):
    return zip(*[seq[n:] for n in range(n)])

print list(ngram(a, 2))

Hope this helps!

--Mark



On 30 April 2014 10:53, Hedieh Ebrahimi <hedieh.ebrahimi at amphos21.com>wrote:

> Hi all,
>
> Imagine I have a list like this:
>
> myList= [1, 7, 19, 1110]
>
> from this list I like to create a list of tuple of ranges like this.
>
> [(1,7),(7,19),(19,1110)]
>
> How can I do this in an efficient way ?
>
> Thanks in advance.
>
> _______________________________________________
> Glasgow mailing list
> Glasgow at python.org
> https://mail.python.org/mailman/listinfo/glasgow
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/glasgow/attachments/20140430/25a486eb/attachment.html>


More information about the Glasgow mailing list