I have the 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 what I need is:
so the result may look 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, but the last last elements are missing
for i in range(0, len(list_a)+1, 6):
if i > 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 would just build a new list by constantly appending to it rather than inserting into an existing list. This should work:
n = len(list_a)
newList = []
for i 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 was no next tuple"
print newList
There was 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 that your example did not indicate what to do in case two if there are no additional tuples. Supposed there are 12 tuples in list_a. Then when you get to the second group of 2, there is no next tuple.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With