how to reset pointer of list in for loop after a condition becomes true in python? -
for r in right: if stack.endswith(r): stack=stack.replace(r,left[right.index(r)])
when if
part gets true
want r
point starting index of right
.
suppose r
pointing 3rd element of right
when if
gets true
, updates stack
, for
loop continues 3rd element of right
. want start for
loop first element of right
whenever stack
updated.
how it?
one cool way use explicit iterator
iterator = iter(right) try: while true: r = next(iterator) if stack.endswith(r): stack = stack.replace(r, left[right.index(r)]) iterator = iter(right) except stopiteration: pass
which in case looks pretty horrible there no "has_next" method iterators, , way know when stop catch exception; , loop not work here because stores reference iterator
but idiomatic python in exact case use else
clause of for
loop break out while:
# loop forever while true: r in right: if stack.endswith(r): stack = stack.replace(r, left[right.index(r)]) # break out of for-loop rerunning while break # else run when r in right consumed else: # break not in loop; breaks while break
Comments
Post a Comment