I have the nested list,
a = [(2,0),(3,0),(4,2),(10,3),(11,5)]
What I want to do is to add the inner-tuple (0,n)
at position n
, where n
is the location of the missing element in a
. The second element in each inner list should increase in increments of one, and if there is a gap then (0,n)
should be inserted at that gap.
So the expected outcome for the list a
is:
a_out = [(2,0),(3,0),(0,1),(4,2),(10,3),(0,4),(11,5)]
I.e since the first and second element in a
is (3,0)
and (4,2)
the so a (0,1)
is inserted between them.
My solution works, but I was wondering if there is a more pythonic way of going about it? I have been looking up Python's itertools library but I can't find a concise solution.
My code so far is:
l1 = [n[1] for n in a]
l2 = range(max(l1)+1)
l3 = [n for n in l2 if not in l1]
zeros = [0]*len(l3)
inserts = zip(zeros,l3)
a_full = a + inserts
a_out = sorted(a_full, key = itemgetter(1))
Can anyone suggest a better solution to this??
EDIT:
In general there may be many elements with the same second inner element (for example the (2,0)
and (3,0)
occuring in a
). However, I can group and sum these together without lose of generality.
The nested list a
can then be represented as,
a_sum = [(5,0),(4,2),(10,3),(11,5)]
By using the code,
a_group = [sum([x for x, y in group]) for key, group in groupby(a, key=itemgetter(1))]
a_sum = zip(output,list(set(l1)))
EDIT II:
The length of a
is always 600, but depending on how the research goes this may increase to of order 10**3.