jk1093 - 2 years ago 97
Python Question

# Create a list of tuples containing adjacent numbers?

I have a list of numbers that looks like this:

``````>>>a = [1, 2, 3, 6, 9, 10]
>>>b = func(a)
>>>print(b)
[(1,2,3), (6,), (9,10)]
``````

basically what I'm looking for is tuples of all runs of consecutive numbers. What would be the fastest way to do this?

Here's a custom generator:

``````def yield_adjacent(lst):
it = iter(lst)
sub = [next(it)]
while True:
try:
n = next(it)
except StopIteration:
yield tuple(sub)
raise
if n - sub[-1] == 1:
sub.append(n)
else:
yield tuple(sub)
sub = [n]
``````

Demo:

``````>>> a = [1, 2, 3, 6, 9, 10]
[(1, 2, 3), (6,), (9, 10)]
>>> a = []
[]
>>> a = [1, 3]
[(1,), (3,)]
>>> a = [1, 3, 4, 9]
[(1,), (3, 4), (9,)]
``````

edit: `for` loop version:

``````def yield_adjacent(lst):
it = iter(lst)
sub = [next(it)]
for n in it:
if n - sub[-1] == 1:
sub.append(n)
else:
yield tuple(sub)
sub = [n]
yield tuple(sub)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download