我想在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