2016-04-14 137 views
0

好的。把這根頭髮拉出來。我整天寫這樣的代碼,不能爲我的生活看到爲什麼這樣做。也許我需要睡眠。變量範圍問題(我認爲)

我的代碼:

gsamp  = 0  # good samples 
    zsamp  = 0  # zero samples 
    nsamp  = 0  # null samples 
    rtotal  = 0 
    rtotalltms = 0 
    pctltms  = 0.0 
    peakh  = 0 
    peakl  = 0 

    for sample in self.rawdata: 
     if "data" not in sample['data']: 
      nsamp += 1 
      continue 
     if not bool(sample['data']['data']): 
      nsamp += 1 
      continue 
     rtotal += sample['data']['value'] 
     gsamp += 1 
     # If I print gsamp here it shows it being correctly incremented 
     for entry in sample['data']['data']: 
      if int(entry['key']) <= thresh: 
       rtotalltms += entry['value'] 
      if gsamp == 1: 
       print "DEBUG gsamp=%d" % gsamp 
       peakh = int(entry['key']) 
       peakl = int(entry['key']) 
       continue 
      if int(entry['key'] > peakh): 
       peakh = int(entry['key']) 
       continue 
      if int(entry['key'] < peakl): 
       peakl = int(entry['key']) 
       continue 

我應該永遠只能看到調試行打印一次。但由於某種原因gsamp正在本地範圍或某事。

當運行此代碼具有30個樣本的數據集,我看到調試行印有gsamp 30次= 1

感謝您的幫助。

回答

0

問題在於你在頂循環中遞增gsamp,因爲你通過sample.rawdata循環,但是接着你又敲了第二個循環sample['data']['data']。這是調試語句正在打印的位置。

如果刪除代碼的其餘部分,你可以看到這是怎麼回事:

[...] 

gsamp += 1 
    # If I print gsamp here it shows it being correctly incremented 
    for entry in sample['data']['data']: 
     if int(entry['key']) <= thresh: 
      rtotalltms += entry['value'] 
     if gsamp == 1: 
      print "DEBUG gsamp=%d" % gsamp 

      [...] 
+0

但gsamp還是在範圍上,它爲什麼不使用相同的gsamp在循環中的下一個更高的水平? – BenH