I was looking at a dataset with a year column. I wanted all the years with matching a particular event. I then get a list of years which is not easy to read:
2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020
It would be much better to display them as:
2010-2013, 2015, 2017-2020
I was looking for a builtin function in Python, but eventually, I wrote this:
import numpy as np
def ranges(array):
start = None
for i, k in zip(np.diff(array, append=[array[-1]]), array):
if i == 1:
if start is None:
start = k
continue
yield(k if start is None else (start, k))
start = None
Is there a more pythonic way that does the same with less?
At the end I could do this:
years = [2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020]
', '.join([f'{x[0]}-{x[1]}' if isinstance(x, tuple) else str(x)
for x in ranges(years)])