python循环只运行一次

时间:2015-08-27 16:08:12

标签: python loops

为什么以下函数仅在仅发送一组数据时运行。我认为每个必须对数据集中的每个值都有意义。

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
}

2 个答案:

答案 0 :(得分:2)

每次调用each.counter_volume时,您都会覆盖d,e和f。如果您希望最终获得大量返回数据,则需要以下内容:

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})

值得注意的是,这假设您的所有数据集都具有相同的长度。要获得更深入的答案,您需要提供一个更深入的问题,询问您要实现的目标。

答案 1 :(得分: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.')