I am trying to merge two list (within a list of list) if a certain conditions are met.
An example:
li = [[18, 19, 20, 21, 22], [25, 26, 27], [59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69]]
li2 = [[15, 16, 17], [32, 33, 34, 35], [89, 90, 91], [95, 96, 97, 98]]
The condition is that if the difference (or the distance rather) between each lists is less than 7 units, the list will be merged. After the list is merged, I would like to fill in the missing numbers.
Hence the expected outcome is as below:
li = [[18, 19, 20, 21, 22, 23, 24, 25, 26, 27], [59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69]]
li2 = [[15, 16, 17], [32, 33, 34, 35], [89, 90, 91, 92, 93, 94, 95, 96, 97, 98]]
This is the current code that I am working on:
new_li = []
for i in np.arange(len(li) - 1):
current_item, next_item = li[i], li[i+1]
if next_item[0] - current_item[-1] <= 7:
new_li.append(current_item + next_item)
else:
new_li.append(next_item)
Which gives me:
new_li = [[18, 19, 20, 21, 22, 25, 26, 27], [59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69]]
And applying the code for the li2
:
new_li2 = [[32, 33, 34, 35], [89, 90, 91], [89, 90, 91, 92, 93, 95, 96, 97, 98]]
Before I can even begin to fill in the missing values, my code is incorrect and can't seem to get the last part of the code correct. Any help or tips to improve my codes is greatly appreciated!