Python 2.7 变量范围问题(我认为)

Python 2.7 变量范围问题(我认为),python-2.7,Python 2.7,嗯。在这件事上把我的头发拔出来。我整天都在写这样的代码,我一辈子都看不出为什么要这样做。也许我需要睡觉 我的代码: gsamp = 0 # good samples zsamp = 0 # zero samples nsamp = 0 # null samples rtotal = 0 rtotalltms = 0 pctltms = 0.0 peakh

嗯。在这件事上把我的头发拔出来。我整天都在写这样的代码,我一辈子都看不出为什么要这样做。也许我需要睡觉

我的代码:

    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=0#好的样本
zsamp=0#零个样本
nsamp=0#空样本
rtotal=0
rtotalltms=0
pctltms=0.0
峰值=0
峰值=0
对于self.rawdata中的示例:
如果“数据”不在样本[“数据”]:
nsamp+=1
持续
如果不是bool(样本['data']['data']):
nsamp+=1
持续
rtotal+=样本['data']['value']
gsamp+=1
#如果我在这里打印gsamp,它将显示它正确递增
对于样本['data']['data']中的条目:
如果int(条目['key'])峰值:
peakh=int(输入['key'])
持续
如果int(条目['key']
我应该只能看到调试行打印一次。但出于某种原因,gsamp正在局部范围内或其他方面

当我用30个样本的数据集运行这段代码时,我看到调试行用gsamp=1打印了30次


谢谢您的帮助。

问题是,当您在
sample.rawdata
中循环时,您正在顶部循环中递增
gsamp
,但随后您遇到了第二个循环,
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

            [...]
[…]
gsamp+=1
#如果我在这里打印gsamp,它将显示它正确递增
对于样本['data']['data']中的条目:

如果int(entry['key'])但gsamp仍在范围内,为什么它不使用与循环中下一个更高级别相同的gsamp呢?