c = [1,2,3,4,5,6,7,8,9,10]
for a,b in func(c):
doSomething()
So func() have to return (1,2) (2,3) (3,4) ... (8,9) (9,10)
Is there a elegant method in python 2.7 to achieve this?
c = [1,2,3,4,5,6,7,8,9,10]
for a,b in func(c):
doSomething()
So func() have to return (1,2) (2,3) (3,4) ... (8,9) (9,10)
Is there a elegant method in python 2.7 to achieve this?
Sure, there are many ways. Simplest:
def func(alist):
return zip(alist, alist[1:])
This spends a lot of memory in Python 2, since zip
makes an actual list and so does the slicing. There are several alternatives focused on generators that offer memory savings, such as a very simple:
def func(alist):
it = iter(alist)
old = next(it, None)
for new in it:
yield old, new
old = new
Or you can get fancier deploying the powerful itertools
instead, as in the pairwise
recipe proposed by @HughBothwell .
The itertools documentation has a recipe for this:
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
then
for a,b in pairwise(c):
doSomething(a, b)
There are many ways
>>> a = [1,2,3,4,5,6,7,8,9,10]
>>> list(zip(a,a[1:]))
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
The other ways are
[(a[i],a[i+1]) for i in range(len(a)-1)]
As you wanter a function you can do
func = lambda a : list(zip(a,a[1:]))
You can use zip
:
>>> def pair(sample_list):
... return zip(sample_list,sample_list[1:])
...
>>> pair(a)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
Or with iter()
that return an iterator , so you can use next()
attribute of iterator in a list comprehension to get the proper pairs , note that in both recipes the second object need to be slice from first element to end [1:]
, and i following you need to slice the main list from leading to end except the last element , because the iterator will chose it :
>>> def pair(sample_list):
... it_a=iter(sample_list[1:])
... return [(i,it_a.next()) for i in sample_list[:-1]]
...
>>> pair(a)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
Try this:
c = list(range(1, 11))
for a, b in zip(c[:-1], c[1:]):
doSomething()