2015-08-27 164 views
0

爲什麼以下函數只運行一次只發送一組數據。我認爲每一個都必須意味着數據集中的每個值。python循環只運行一次

data_checkpoint_size = cclient.samples.list(meter_name ='checkpoint.size') 
data_checkpoint_length = cclient.samples.list(meter_name ='checkpoint.length') 
data_checkpoint_pause = cclient.samples.list(meter_name ='checkpoint.pause') 


def counterVolume(data_checkpoint_size, data_checkpoint_length, data_checkpoint_pause): 
    for each in data_checkpoint_size: 
    d = each.counter_volume 
    for each in data_checkpoint_length: 
    e = each.counter_volume 
    for each in data_checkpoint_pause: 
    f = each.counter_volume 
    pubnub.publish(channel='channel', message= {'checkpoint_size': d, 'checkpoint_length': e, 'checkpoint_pause': f}) 

counterVolume(data_checkpoint_size, data_checkpoint_length, data_checkpoint_pause) 

而且我只得到以下結果而不是系列數據。 checkpoint_size,checkpoint_length和checkpoint_pause三種不同的米,這些都是

{ 
    checkpoint_length: 75, 
    checkpoint_size: 5000, 
    checkpoint_pause: 50 
} 
+1

嗯,一方面,我們需要看看你是怎麼稱呼它的。 –

+0

你是否在談論'pubnub.publish'只被調用一次?它將會被調用一次,因爲它在循環之外。 –

+1

您的d,e和f通過for循環重新分配。 – ismailsunni

回答

2

就像@ismailsunni說的,你的變量被重新分配。這使得所有的數據都是相同長度的假設,但它應該工作:

def counterVolume(data_checkpoint_size, data_checkpoint_length, data_checkpoint_pause): 
    for i, size in enumerate(data_checkpoint_size): 
     length = data_checkpoint_length[i] 
     pause = data_checkpoint_pause[i] 
     message = { 
      'checkpoint_size': size .counter_volume, 
      'checkpoint_length': length.counter_volume, 
      'checkpoint_pause': pause.counter_volume, 
     } 
     pubnub.publish(channel='channel', message=message) 

我測試,以確保它們都是一樣的長度第一,提高特定異常(所以它更容易調試):

size_len = len(data_checkpoint_size) 
length_len = len(data_checkpoint_length) 
pause_len = len(data_checkpoint_pause) 

if size_len != length_len or length_len != pause_len: 
    raise Exception('Custom exception message.') 
2

要覆蓋d,E三個不同的數據流,並且每個時間F each.counter_volume被調用。如果你希望有很多返回的數據集合的結束了,你需要這樣的事:

for i in range(data_checkpoint_size): 
    d = data_checkpoint_size[i].counter_volume 
    e = data_checkpoint_length[i].counter_volume 
    f = data_checkpoint_pause[i].counter_volume 
    pubnub.publish(channel='channel', message= {'checkpoint_size': d, 'checkpoint_length': e, 'checkpoint_pause': f}) 

值得注意的是,這裏假設你的所有數據集的長度相等。要獲得更深入的答案,您需要提供一個更深入的問題,涉及您嘗試實現的目標。