Search code examples
pythonalgorithmlistrangecontinuous

Identify groups of continuous numbers from consecutive list in python


What is the most efficient way in python for picking multiple n consecutive integers from n consecutive list, picking up one integer from each list. Here n is quite large..say in the order of 100s.

L1 = [5,3,2,7,1]
L2 = [3,5,6,8,9,21,2]
L3 = [5,3,6,7,3,9]

I'd like to print out the ranges of consecutive integers from consecutive lists, where first element is picked up from first list, second element from second list and so on and so forth:

Candidate solution [5,6,7], [1,2,3], [7,8,9]

Solution

  • L1 = [5,3,2,7,1]
    L2 = [3,5,6,8,9,21,2]
    L3 = [5,3,6,7,3,9]
    cons_l = []
    L = [L2] + [L3] #+[L4] #+ ...+ ..... ### Add any number of list here..
    
    j = 0
    for l1 in L1:
       cons_l.append([])
       cons_l[j].append(l1)
       for l in range(0, len(L)):
          if l1+l+1 in L[l]:
             cons_l[j].append(l1+l+1)
          else:
             del cons_l[j]
             j -= 1
             break
       j += 1
    print cons_l