Matplotlib动画的生成器函数

3

我正在尝试为matplotlib动画生成数据。
我有一个data_gen函数用于matplotlib的"animation.FuncAnimation"函数,它被调用如下:

ani = animation.FuncAnimation(fig, update, frames=data_gen, init_func=init, interval=10, blit=True)

我的代码长这样:

def func(a):
    a += 1
    return a

b = 0

def data_gen():
    global b
    c = func(b)
    b = c
    yield c

很遗憾,这并不是我想要的!例如:
print(data_gen().__next__())
print(data_gen().__next__())
print(data_gen().__next__())

for k in data_gen():
    print(k)

...会生成以下输出:

1
2
3
4

我原以为for循环会一直运行,但它并没有。(它在4处停止。)
我需要的行为是:
(1)为b设置初始值
(2)每次生成器运行时更新b
非常感谢您的建议!
3个回答

2
每次调用data_gen()都会设置一个新的生成器,您只需要继续使用相同的生成器对象即可。此外,没有必要显式维护全局状态,这就是生成器为您完成的任务。
def data_gen(init_val):
    b = init_val
    while True:
        b += 1
        yield b

gen = data_gen(3)
print next(gen)
print 'starting loop'
for j in gen:
    print j
    if j > 50:
        print "don't want to run forever, breaking"
        break

仍然无法工作,因为生成器中没有循环。它只会产生一次。 - M4rtini
@M4rtini 你是对的,被其他问题分心了,并且对全局状态感到困惑... - tacaswell
@tcaswell 这非常有帮助。然而,在animation.FuncAnimation函数调用中将参数包含到data_gen中似乎并不起作用。如果我能够缩小问题的来源,我会再提出另一个问题。再次感谢。 - Riccati
@tcaswell 嗯...这已经远离了最初的问题,但错误是:TypeError: 'generator'对象没有len()。这发生在matplotlib\animation.py中的"self.save_count = len(frames)"。 - Riccati
啊,我刚刚修复了那个 bug.... bug: https://github.com/matplotlib/matplotlib/issues/1769 PR: https://github.com/matplotlib/matplotlib/pull/2634 但它还没有被合并到主分支... - tacaswell
显示剩余2条评论

0
当我像这样将无限循环添加到 data_gen 中时:
b=0
def data_gen():
    global b
    while True:
        b+=1
        yield b

我使用Python 3.3,但结果对于2.x版本应该是相同的。

next(data_gen())
> 1
next(data_gen())
>2
next(data_gen())
>3

list(zip(range(10), data_gen()))
> [(0, 4), (1, 5), (2, 6), (3, 7), (4, 8), (5, 9), (6, 10), (7, 11), (8, 12), (9, 13)]

最后,如果我这样做

for i in data_gen():
    print(i)

代码不断地打印数字


0
def func(a):
    a += 1
    return a

b = 0

def data_gen():
    global b
    while 1:
          c = func(b)
          b = c
          yield c

>>> gen.next()
    1
>>> gen.next()
    2
>>> gen.next()
    3
>>> gen.next()
    4
>>> gen.next()
    5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接