2017-07-29 71 views
4

我想在yield語句中展開一個元組,但是我得到了一個SyntaxError。這甚至是可能的,還是僅用於函數調用的運算符?如何在收益中擴展元組?

這裏是下面一個例子:

class Inner(object): 
    def __init__(self): 
     self._vals = {'a': 1, 
         'b': 2, 
         'c': 3, 
         'd': 4} 

    def __iter__(self): 
     for key, val in self._vals.items(): 
      yield key, val 

class Outer(object): 
    def __init__(self): 
     self._morevals = {"foo": Inner(), 
          "bar": Inner()} 

    def __iter__(self): 
     for key, moreval in self._morevals.items(): 
      for val in moreval: 
       yield key, *val # !!! <--- This is where the error is 

object_under_test = Outer() 

for outer_key, inner_key, inner_value in object_under_test: 
    print("{} {} {}".format(outer_key, inner_key, inner_value)) 

    # Want: 
    # foo a 1 
    # foo b 2 
    # foo c 3 
    # foo d 4 
    # bar a 1 
    # bar b 2 
    # bar c 3 
    # bar d 4 

相反,我得到這個錯誤:

yield key, *val 
      ^
SyntaxError: invalid syntax 

回答

8

添加括號,無論是周圍的元組:

yield (key, *val) 

yield是這裏的特殊之處在於表格只接受表達式列表,而不是starred_list form

5

您需要將它加括號。總之,使用方法:

yield (key, *val) 

或者,你可以通過使用yield from與理解縮短。總而言之,你__iter__看起來像:

def __iter__(self): 
    items = self._morevals.items() 
    yield from ((k, *v) for k, vals in items for v in vals) 

同樣,使用yield fromClassOne.__iter__

def __iter__(self): 
    yield from self._vals.items()