【问题标题】:generator function for matplotlib animationmatplotlib 动画的生成器函数
【发布时间】:2013-12-19 21:21:33
【问题描述】:

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

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

非常感谢所有建议!

【问题讨论】:

    标签: python animation matplotlib generator


    【解决方案1】:

    每次调用data_gen() 都会设置一个new 生成器,您只需要继续使用same 生成器对象即可。也没有理由明确维护全局状态,这就是生成器为您所做的:

    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 你说得对,被其他问题分心了,被全局状态弄糊涂了......
    • @tcaswell 这很有帮助;但是,包含 data_gen 的参数似乎在 animation.FuncAnimation 函数调用中不起作用。如果我能缩小问题的根源,我会问另一个问题。再次感谢。
    • 你应该把它叫做FuncAnimation(..., frames=gen_data(3),...)。它会给您带来什么错误?
    • @tcaswell 好吧...这与原始问题相去甚远,但错误是:TypeError: object of type 'generator' has no len() 这发生在 matplotlib\animation 中。 py "self.save_count = len(frames)"
    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:

      当我像这样向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)
      

      代码继续打印数字

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-27
        • 2022-01-26
        • 2014-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多