Suppose I have a list like this:
lst = [1, 3, 4, 5, 8, 10, 14, 20, 21, 22, 23, 40, 47, 48]
I need to extract the elements which have a difference of one. I need final output to look like this:
[[3, 4, 5], [20, 21, 22, 23], [47, 48]]
Here is what I have tried so far for this particular problem which has yielded some progress but doesn't achieve 100% of what I need:
final_list = []
for i in range(len(lst)):
sub_list = []
for ii in range(i, len(lst)):
prev_num = lst[ii-1]
if lst[ii] - prev_num == 1:
# print(lst[ii], end=",")
sub_array.append(lst[ii])
else:
break
if sub_list:
final_list.append(sub_list)
print(final_list)
Output:
[[4, 5], [5], [21, 22, 23], [22, 23], [23], [48]]