三重嵌套循环(while循环内部for循环内部循环)

时间:2013-03-01 08:54:49

标签: python nested-loops

我正在尝试使我的三重嵌套循环工作。

我的代码就像:

c = 4
y1 = []
m1 = []
std1 = []
while c < 24:
        c = c + 1
        a = []
        f.seek(0, 0)    
        for columns in ( raw.strip().split() for raw in f ):
                a.append(columns[c])    
                x = np.array(a, float)    
        not_nan = np.logical_not(np.isnan(x))    
        indices = np.arange(len(x))    
        interp = interp1d(indices[not_nan], x[not_nan], kind = 'nearest')    
        p = interp(indices)

        N = len(p)
        dt = 900.0 #Time step (seconds)
        fs = 1.0 / dt #Sampling frequency
        KA,PSD = oned_Fourierspectrum(p,dt) # Call Song's 1D FS function
        time_axis = np.linspace(0.0, N, num = N, endpoint = False) * 15 / (60 * 24)
        plot_freq = 24 * 3600.0 * KA #Convert to cycles per day
        plot_period = 1.0 / plot_freq # convert to days/cycle
        fpsd = plot_freq * PSD
        d = -1
        while d < 335:
                d = d + 1
                y = fpsd[d]
                y1 = y1 + [y]
                m = np.mean(y1)
        m1 = m1 + [m]
print m1

我的目的是列出[mean(fpsd[0]), mean(fpsd[1]), mean(fpsd[2]).. mean(fpsd[335])]。每个y1都是fpsd[d]的列表。

我检查过;它在第二次循环之前工作得很好,我可以获得fpsd[d]的单独均值。然而,对于第二个完整循环,它产生肯定错误的数字。 你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

如果你想让m1成为平均值的累积列表,那么最后一行需要缩进到最后的while块内。

while d <335:     
    d = d + 1     
    y = fpsd[d]     
    y1 = y1 + [y]       
    m = np.mean(y1)
    m1 = m1 + [m]