I was wondering that whether there’s a way to refactor the following codes
first_run = True
for i in gen:
if first_run:
last_head = i[1]
last_tail = i[2]
last_chrom = i[0]
first_run = False
else:
func(i[1], last_head)
func(i[1], last_tail)
last_head = i[1]
last_tail = i[2]
last_chrom = i[0]
The essential point of your loop seems to be performing some operation on pairs of consecutive elements of the iterable. So I would look to the function
pairwisewhose definition is given in theitertoolsmodule documentation:Note that this is not an actual
itertoolsfunction, you will have to copy and paste the implementation into your code. Anyway, with this function, your loop can be implemented like so: