如何在收益中扩展元组?

时间:2017-07-29 18:23:47

标签: python python-3.x generator yield

我正在尝试在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

2 个答案:

答案 0 :(得分:8)

在元组周围添加括号:

yield (key, *val)

yield在这里很特别,因为表单只接受表达式列表,而不是starred_list form

答案 1 :(得分: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 from中使用ClassOne.__iter__

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