为什么以下Python代码会引发错误
TypeError: type object argument after * must be a sequence, not generator
如果我评论发电机f中的第一条(无用)线,一切正常吗?
from itertools import izip
def z():
for _ in range(10):
yield _
def f(z):
for _ in z: pass # if I comment this line it works! (??)
for x in range(10):
yield (x,10*x,100*x,1000*x)
iterators = izip(*f(z))
for it in iterators:
print list(it)
N.B。我实际上要做的是,使用单个生成器,返回多个迭代器(尽可能多的我将作为参数传递给生成器)。我发现这样做的唯一方法是产生元组并对它们使用izip() - 对我来说是黑魔法。
答案 0 :(得分:27)
这很有趣:当您将z
传递给f
时,您忘了致电iterators = izip(*f(z()))
:
f
所以for _ in z: pass # z is a function
试图迭代一个函数对象:
TypeError: 'function' object is not iterable
这引发了一个TypeError:
# ceval.c
static PyObject *
ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
{
...
t = PySequence_Tuple(stararg);
if (t == NULL) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_Format(PyExc_TypeError,
"%.200s%.200s argument after * "
"must be a sequence, not %200s",
PyEval_GetFuncName(func),
PyEval_GetFuncDesc(func),
stararg->ob_type->tp_name);
...
Python内脏抓住它并用一个令人困惑的错误消息重新加注。
{{1}}