Iterate over all pairs of consecutive items in a list
Just use zip
>>> l = [1, 7, 3, 5]
>>> for first, second in zip(l, l[1:]):
... print first, second
...
1 7
7 3
3 5
If you use Python 2 (not suggested) you might consider using the izip
function in itertools
for very long lists where you don't want to create a new list.
import itertools
for first, second in itertools.izip(l, l[1:]):
...
R iterate over consecutive pairs in a list
We can remove the first
and last
elements and concatenate in Map
Map(c, v1[-length(v1)], v1[-1])
#[[1]]
#[1] 1 2
#[[2]]
#[1] 2 3
#[[3]]
#[1] 3 4
Or rbind
and use asplit
asplit(rbind(v1[-length(v1)], v1[-1]), 2)
python - iterate over all pairs of consecutive items with gaps
One fairly easy way to do it is to think about it in terms of the index rather than the list items itself. Start with:
import itertools
list(itertools.combinations(range(len(mylist)), 3)
This gets you all the possible index triple combinations in a list with the length of your list. Now you want to filter them to exclude any where the last index is 4 or more away from the first:
list(filter(lambda seq: (seq[-1] - seq[0]) <= 4, itertools.combinations(l, 3)))
This gets you the indeces you want. So now you can get the triples you need based on the indeces:
[[mylist[i] for i in seq] for seq in filter(lambda seq: (seq[-1] - seq[0]) < 4, itertools.combinations(l, 3))]
which produces:
[[1, 6, 4], [1, 6, 9], [1, 4, 9], [6, 4, 9], [6, 4, 2], [6, 9, 2], [4, 9, 2]]
Iterate over all pairs (or triples) of consecutive elements with wrap-around
Probably you are looking for something like this:
mylist = [1,2,3,4,5,6,7,8,9,10]
for previous, current, following in zip([mylist[-1]] + mylist[:-1], mylist, mylist[1:] + [mylist[0]]):
print(previous, current, following)
Here I simply used zip and list concatenation.
Iterate consecutive elements in a list in Python such that the last element combines with first
You can simply extend the second list in zip()
with a list with only the first item, something like:
for first, second in zip(L, L[1:] + L[0:1]): # or simply zip(L, L[1:] + L[:1])
print([first, second])
Iterating over every two elements in a list
You need a pairwise()
(or grouped()
) implementation.
def pairwise(iterable):
"s -> (s0, s1), (s2, s3), (s4, s5), ..."
a = iter(iterable)
return zip(a, a)
for x, y in pairwise(l):
print("%d + %d = %d" % (x, y, x + y))
Or, more generally:
def grouped(iterable, n):
"s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
return zip(*[iter(iterable)]*n)
for x, y in grouped(l, 2):
print("%d + %d = %d" % (x, y, x + y))
In Python 2, you should import izip
as a replacement for Python 3's built-in zip()
function.
All credit to martineau for his answer to my question, I have found this to be very efficient as it only iterates once over the list and does not create any unnecessary lists in the process.
N.B: This should not be confused with the pairwise
recipe in Python's own itertools
documentation, which yields s -> (s0, s1), (s1, s2), (s2, s3), ...
, as pointed out by @lazyr in the comments.
Little addition for those who would like to do type checking with mypy on Python 3:
from typing import Iterable, Tuple, TypeVar
T = TypeVar("T")
def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]:
"""s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ..."""
return zip(*[iter(iterable)] * n)
How can I iterate over overlapping (current, next) pairs of values from a list?
Here's a relevant example from the itertools module docs:
import itertools
def pairwise(iterable):
"s -> (s0, s1), (s1, s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
For Python 2, you need itertools.izip
instead of zip
:
import itertools
def pairwise(iterable):
"s -> (s0, s1), (s1, s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
How this works:
First, two parallel iterators, a
and b
are created (the tee()
call), both pointing to the first element of the original iterable. The second iterator, b
is moved 1 step forward (the next(b, None)
) call). At this point a
points to s0 and b
points to s1. Both a
and b
can traverse the original iterator independently - the izip function takes the two iterators and makes pairs of the returned elements, advancing both iterators at the same pace.
One caveat: the tee()
function produces two iterators that can advance independently of each other, but it comes at a cost. If one of the iterators advances further than the other, then tee()
needs to keep the consumed elements in memory until the second iterator comsumes them too (it cannot 'rewind' the original iterator). Here it doesn't matter because one iterator is only 1 step ahead of the other, but in general it's easy to use a lot of memory this way.
And since tee()
can take an n
parameter, this can also be used for more than two parallel iterators:
def threes(iterator):
"s -> (s0, s1, s2), (s1, s2, s3), (s2, s3, 4), ..."
a, b, c = itertools.tee(iterator, 3)
next(b, None)
next(c, None)
next(c, None)
return zip(a, b, c)
Python group consecutive elements of a list into two's without repetition
What we do is we first flatten the list and then we index the flattened list to the 2d list
l1 = [[0,1],[0,1,2,3,4,5,6,7],[0,1,2,3]]
def fix(l1):
l1 = [item for sublist in l1 for item in sublist]
l1 = [l1[i:i+2] for i in range(0, len(l1), 2)]
return l1
l1 = fix(l1)
print(l1)
Output:
[[0, 1], [0, 1], [2, 3], [4, 5], [6, 7], [0, 1], [2, 3]]
Scala iterate over two consecutive elements of a list
If I understand correctly you probably want to iterate over a sliding window.
list.sliding(2).map{
case List(a, b) => a.diff(b)
case List(a) => a
}.toList
Alternatively you might also want grouped(2)
which partitions the list into groups instead.
Related Topics
How to Know If an Object Has an Attribute in Python
Using Pip to Install Packages to Anaconda Environment
Http Requests and JSON Parsing in Python
Getting Realtime Output Using Subprocess
Checking Whole String with a Regex
Weird Timezone Issue with Pytz
How Does Asyncio Actually Work
How to Remove Convexity Defects in a Sudoku Square
Python: List VS Dict for Look Up Table
Simple Prime Number Generator in Python
Python Subprocess/Popen with a Modified Environment
How to Tail a Log File in Python
How to Switch to New Window in Selenium for Python
How to Use String.Replace() in Python 3.X
How to Efficiently Compare Two Unordered Lists (Not Sets)