2010/3/5 Emad Nawfal (عمـ نوفل ـاد) <emadnaw...@gmail.com>:
>
>
> Here is a general solution that I also took from the Tutor list some time
> ago. It allows you to have consequences of (any) length.
>
>>>> def makeVectors(length, listname):
> ...     """takes the length of the vector and a listname returns vectors"""
> ...     vectors = (listname[i:i+length] for i in
> range(len(listname)-length+1))
> ...     return vectors
> ...
>>>> myList = [1,2,3,4,5,6]
>
>>>> bigrams = makeVectors(2, myList)
>>>> bigrams
> <generator object <genexpr> at 0xb7227e64>
>>>> for bigram in bigrams: print bigram
> ...
> [1, 2]
> [2, 3]
> [3, 4]
> [4, 5]
> [5, 6]

Except the OP requested pairs (1, 2), (3, 4), i.e. with no duplicate
elements. Here is a generator that does what you need:

def pairs(seq):
    it = iter(seq)
    try:
        while True:
            yield it.next(), it.next()
    except StopIteration:
        return

Hugo
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to