2013-12-19 36 views
0

我正在嘗試生成matplotlib動畫的數據。
我有matplotlib的「animation.FuncAnimation」功能的data_gen函數被調用是這樣的:matplotlib動畫的生成器函數

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) set initial value for b

(2) update b each time the generator runs

所有建議,不勝感激!

回答

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 
+0

仍然不會工作,因爲在發電機中沒有環路。它只會產生一次。 – M4rtini

+0

@ M4rtini你的權利,被其他問題分散注意力,並被全球國家所迷惑...... – tacaswell

+0

@tcaswell這是非常有幫助的;但是,包括data_gen的參數在animation.FuncAnimation函數調用中似乎不起作用。如果我能縮小麻煩的根源,我會再問另一個問題。再次感謝。 – Riccati

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