【发布时间】:2014-01-08 17:58:09
【问题描述】:
我正在通过调用使用 matplotlib 动画:
plot = animation.FuncAnimation(fig, update, frames=data_gen(a), init_func=init, interval=10, blit=True)
这里,“a”是 data_gen 函数的初始值,如下所示:
data_gen(x)
old_x = x
while True:
new_x = func(old_x)
old_x = new_x
yield new_x
此代码的目的是让 data_gen 在每次更新动画图时为 new_x 生成一个新值。
但是……这反而发生了:
animation.py 在 FuncAnimation 类的 init() 方法中引发错误。
问题发生在这段代码中:
elif iterable(frames):
self._iter_gen = lambda: iter(frames)
self.save_count = len(frames)
错误是“TypeError: 'generator' 类型的对象没有 len()”
看起来 data_gen 是可迭代的,但它没有 len()。
下面是 FuncAnimation 类中 init() 方法的更多代码:
# Set up a function that creates a new iterable when needed. If nothing
# is passed in for frames, just use itertools.count, which will just
# keep counting from 0. A callable passed in for frames is assumed to
# be a generator. An iterable will be used as is, and anything else
# will be treated as a number of frames.
if frames is None:
self._iter_gen = itertools.count
elif isinstance(frames, collections.Callable):
self._iter_gen = frames
elif iterable(frames):
self._iter_gen = lambda: iter(frames)
self.save_count = len(frames)
else:
self._iter_gen = lambda: iter(list(range(frames)))
self.save_count = frames
我不确定为什么我的 data_gen 不是 collections.Callable。如果是,那么 len(frames) 将永远不会发生。
任何关于我应该怎么做的建议都将不胜感激!
【问题讨论】:
-
参见:错误:github.com/matplotlib/matplotlib/issues/1769 PR:github.com/matplotlib/matplotlib/pull/2634(感谢@tcaswell)
标签: python animation matplotlib iterable callable