5

我正在尝试使用生成器进行类型转换,但是一旦成功产生值,我想移动到迭代器中的下一个元素。在表达式成功的情况下,我当前的尝试将产生多个值:

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

这是如何实现的?

4

4 回答 4

4

您应该能够continue像其他任何循环一样执行此循环:

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

作为旁注,我一直认为continue这个控制结构是一个奇怪的名字......

而且,这是您更正的代码:

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)
于 2012-07-19T18:41:03.440 回答
4

我不知道它是否在每个 try 块调用 next(),但如果这是你关心的问题,你为什么不这样做

try:
  item =  int(item)
except (ValueError, TypeError) as WrongTypeerror
   try:
       item = float(item)
   except (ValueError, TypeError) as WrongTypeError
       pass
yield item
于 2012-07-19T18:42:37.280 回答
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)
于 2012-07-19T20:28:22.867 回答
0

这有效:

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]
于 2012-07-19T18:47:29.730 回答