Given multiple lists, how to find the values between neighboring lists?

Question:

I have multiple lists of increasing numbers. The elements in each list are strictly greater than those in its previous neighbor. i.e. [1,2,3], [6,7,8], [10,11,12].

How to find the numbers between neighboring lists? In this case, the results would be [4,5], [9].

If there are only two lists, I can use something like

a = [1,2,3]
b = [4,5,6]
result = list(range(a[-1]+1,b[0]))

but I can’t think of a simple and fast way to construct a loop to do this if I have more than two lists.

Asked By: sensationti

||

Answers:

Assuming that the lists are sorted and that the elements in each list are strictly increasing you can use a loop to iterate over the indices of the lists and uses the range() function to generate a list of numbers between the last element of the current list and the first element of the next list. The results are appended to the results array:

def find_gaps(lists):
    gaps = []
    for i in range(len(lists) - 1):
        gap = list(range(lists[i][-1] + 1, lists[i + 1][0]))
        gaps.append(gap)
    return gaps


lists = [[1, 2, 3], [6, 7, 8], [10, 11, 12]]
print(find_gaps(lists))

The resulting list of arrays will contain the numbers between neighboring lists: [[4, 5], [9]]. The complexity of the find_gaps() function is O(n), where n is the number of lists.

Answered By: kaiffeetasse

You can try the following:

    a,b,c=[1,2,3], [6,7,8], [10,11,12]
    c=[a,b,c]
    result=[]
    for i in range(len(c)-1):
        result.append(list(range(c[i][-1]+1,c[i+1][0])))
    
    print(result)

Answered By: oswaldo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.