每次迭代只产生一次

时间:2012-07-19 18:33:30

标签: python generator

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

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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:4)

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

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

答案 2 :(得分: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]

答案 3 :(得分: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)