I'm trying to do type conversions using a generator, but I want to move to the next element in the iterator once I successfully yield a value. My current attempt will yield multiple values in cases where the expressions are successful:
def type_convert(data):
for item in data:
try:
yield int(item)
except (ValueError, TypeError) as WrongTypeError:
pass
try:
yield float(item)
except (ValueError, TypeError) as WrongTypeError:
pass
yield item
How is this accomplished?
You should be able to continue
this loop just like any other:
try:
yield int(item)
continue
except (ValueError, TypeError) as WrongTypeError:
pass
As a side note, I've always thought continue
was a strange name for this control structure...
And, here's your corrected code in action:
def type_convert(data):
for item in data:
try:
yield int(item)
continue
except (ValueError, TypeError) as WrongTypeError:
pass
try:
yield float(item)
continue
except (ValueError, TypeError) as WrongTypeError:
pass
yield item
for a in type_convert(['a','1','1.0']):
print (a)
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