Home > Software design >  How can i add consecutives elements in a list composed of the consecutive value of the previous elem
How can i add consecutives elements in a list composed of the consecutive value of the previous elem

Time:12-08

I would like to create a new list that takes my existing list L by adding the consecutive value of the previous element (first term) and a zero in the second term for an entire list.

Input:

L = [(1, 12), (3, 14), (6, 19), ..., (7412, 15), (7415, 15)]

I would like this output :

L = [(1, 12), (2, 0) ,(3, 14), (4, 0), (5, 0), (6, 19), ... , (7412, 15), (7413, 0), (7414, 0), (7415, 15)]

CodePudding user response:

This should do the job. Not the most readable, though.

L = [(1, 12), (3, 14), (6, 19)]
keys = {key[0]:idx for (idx, key) in enumerate(L)}
[(x, L[keys[x]][1]) if x in keys.keys() else (x, 0) for x in range(1, L[-1][0]   1)]

Output:

[(1, 12), (2, 0), (3, 14), (4, 0), (5, 0), (6, 19)]

Instead of list-comprehension simple for-loops could be used to make it a bit more readable, but also take up more lines of code.

CodePudding user response:

You can

(i) use set.difference to find the numbers that are not leading any tuples in L and create a tuple with each and put all to a list,

(ii) add it to the original L and sort the new list on the first elements.

L = [(1, 12), (3, 14), (6, 19)]
z = list(zip(*L))[0]
out = [(i,0) for i in set(range(z[0],z[-1] 1)).difference(z)]
out = sorted(L   out)

Output:

[(1, 12), (2, 0), (3, 14), (4, 0), (5, 0), (6, 19)]
  • Related