我正在尝试使用生成器进行类型转换,但是我想在成功生成值后移动到迭代器中的下一个元素。在表达式成功的情况下,我当前的尝试将产生多个值:
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
这是如何完成的?
答案 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)