def yield_and_skip(iterable,skip):
for i in iterable:
print(skip(i))
for x in range(skip(i)):
pass
yield i
I'm defning a function called skip_yield, which produces a value from the iterable but then it then skips the number of values specified when the function argument is called on the just-produced value. It takes 2 parameters: skip is a small function. However, if I try to do this:
print(''.join([v for v in yield_and_skip('abbabxcabbcaccabb',lambda x : {'a':1,'b':2,'c':3}.get(x,0))]))
it gives me:
abbabcabbcaccabb
but it should give me:
abxccab
Any idea?
First of all, pass
doesn't do anything to iterable
. If you need to advance the iterator, call the next
function on iterator object skip(i)
number of times (either directly or indirectly).
Also, next
call may raise StopIteration
, thus terminating the loop. yield i
before advancing the iterator or provide the second argument, to make next
swallow the exception.
Your code would look like
def yield_and_skip(iterable, skip):
it = iter(iterable)
for i in it:
for _ in range(skip(i)):
next(it, None)
yield i