python - Insert values in lists following a pattern -
i have following example list:
list_a = [(1, 6), (6, 66), (66, 72), (72, 78), (78, 138), (138, 146), (154, 208), (208, 217), (217, 225), (225, 279), (279, 288) ..... ]
and need is:
- after every 6 elements on list, insert in place new tuple formed last number of previous one, , first number in previous 6 tuples.
- after tuple inserted, insert formed first number of previous 1 plus 1, , last number of previous 1 , first number of next tuple.
so result may like:
list_a = [(1, 6), (6, 66), (66, 72), (72, 78), (78, 138), (138, 146), (146, 1), # <- first part (147, 154), # <- second part (154, 208), (208, 217), (217, 225), (225, 279), (279, 288) (288, 147) # <- first part ..... ]
i have tried this, last last elements missing
for in range(0, len(list_a)+1, 6): if > 0: list_a.insert(i, (list_a[i - 1][1], list_a[i - 6][0])) list_a.insert(i + 1, (list_a[i - 1][1] + 1, list_a[i + 1][0],))
i build new list appending rather inserting existing list. should work:
n = len(list_a) newlist = [] in range(0,n, 6): newlist.append(list_a[i:i+6] ) newtuple1 = (newlist[-1][1], newlist[i][0]) newlist.append(newtuple1) try: newtuple2 = (newtuple1[0] + 1, list_a[i+6][0]) newlist.append(newtuple2) except indexerror: print "there no next tuple" print newlist
output
there no next tuple [(1, 6), (6, 66), (66, 72), (72, 78), (78, 138), (138, 146), (146, 1), (147, 154), (154, 208), (208, 217), (217, 225), (225, 279), (279, 288), (300, 400), (400, 146)]
note example did not indicate in case 2 if there no additional tuples. supposed there 12 tuples in list_a. when second group of 2, there no next tuple.
hope helps.
Comments
Post a Comment