Exit only once per iteration

I am trying to do type conversions with a generator, but I want to move on to the next element in an iterator as soon as I successfully assign a value. My current attempt will give several 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 achieved?

+5
source share
4 answers

You should be able to do continuethis loop, like any other:

try:
    yield int(item)
    continue
except (ValueError, TypeError) as WrongTypeError:
    pass

As a note, I always thought that continuewas a strange name for this management structure ...

And here is 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)
+4
source

I don't know if this calls next () in every try block, but if that bothers you, why not do it

try:
  item =  int(item)
except (ValueError, TypeError) as WrongTypeerror
   try:
       item = float(item)
   except (ValueError, TypeError) as WrongTypeError
       pass
yield item
+4
source

:

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

:

>>> list(type_convert(["13", 3.5, True]))
[13, 3, 1]
0

:

def type_convert(*args):
    datatypes = []
    for arg in args:
        if type(arg) == type(type):
            datatypes += [arg]
        else:
            data = arg
    for item in data:
        for datatype in datatypes:
            try:
                yield datatype(item)
                break
            except (ValueError, TypeError) as WrongTypeError:
                pass
        else:
            yield item  # unable to convert to any datatype

for a in type_convert(int, float, ['a','1','1.0']):
    print (a)
0

All Articles