2012-07-19 162 views
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 

這是如何實現的?

+0

我我很確定我只是缺少了一些東西,但是你的選擇是什麼情況'int'會失敗,但你的轉換成'float'會成功嗎? – 2012-07-19 18:43:35

+2

@NolenRoyalty - 考慮字符串:''1.0'' – mgilson 2012-07-19 18:43:55

+0

@mgilson非常有意義,謝謝:D – 2012-07-19 18:44:30

回答

4

你應該能夠continue這個循環,就像任何其他:

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

作爲一個方面說明,我一直認爲continue是這個控制結構一個陌生的名字...

而且,這裏是在您的行動糾正代碼:)在每個try塊

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

我不知道它下一次調用(,但如果這是喲關注U,你爲什麼不這樣做

try: 
    item = int(item) 
except (ValueError, TypeError) as WrongTypeerror 
    try: 
     item = float(item) 
    except (ValueError, TypeError) as WrongTypeError 
     pass 
yield item 
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] 
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)