I want to iterate over two lists in such a way that I can take an arbitrary number of values from one list and maintain my position in the other.
I've used indexes to store the current position in each list, then a while loop to go over them, but this definitely isn't very pythonic.
def alternate_iterate(a,b,cond=lambda x, y : x > y):
pos_a = 0
pos_b = 0
retval = []
while(True):
if(pos_a == len(a) and pos_b == len(b)):
break
if(pos_a < len(a) and cond(a[pos_a],b[pos_b])):
retval += [a[pos_a]]
pos_a += 1
elif(pos_b < len(b)):
retval += [b[pos_b]]
pos_b += 1
return retval
#example usage
print(alternate_iterate(['abc','abcd','ab','abc','ab'],
['xy','xyz','x','xyz'],
cond=lambda x,y: len(x) > len(y))
This should print ['abc','abdc','xy','xyz','ab','abc','ab','x','xyz']
, where you don't have a perfect 1:1 alternating order. The order of the elements and the type of the elements should only depend on whatever cond
is defined as.