matplotlib动画的生成器功能 [英] generator function for matplotlib animation

查看:106
本文介绍了matplotlib动画的生成器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为matplotlib动画生成数据。

我有一个matplotlib的 animation.FuncAnimation函数的data_gen函数,如下所示:

I'm trying to generate data for a matplotlib animation.
I have a data_gen function for matplotlib's "animation.FuncAnimation" function that is called like this:

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

我的代码具有以下形式:

My code has this form:

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

b = 0

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

不幸的是,这没有做我想要的!例如,

Unfortunately, this does not do what I want! For example,

print(data_gen().__next__())
print(data_gen().__next__())
print(data_gen().__next__())

for k in data_gen():
    print(k)

...产生以下输出:

... produces this output:

1
2
3
4

我期望for循环将永远运行,但不会。 (它在4处停止。)

I was expecting that the for loop would run forever, but it does not. (It stops at 4.)

我需要的行为是:


(1)为b

(1) set initial value for b

设置初始值(2)每次发电机运行时更新b

(2) update b each time the generator runs

非常感谢所有建议!

推荐答案

每次调用 data_gen()可以设置 new 生成器,您只需要继续使用 same 生成器对象即可。也没有理由明确维护全局状态,即生成器为您执行的操作:

Each time you call data_gen() in sets up a new generator, you just need to keep using the same generator object. There is also no reason do explicitly maintain a global state, that is what the generator does for you:

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

这篇关于matplotlib动画的生成器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆