嵌套while循环只迭代一次

时间:2017-02-10 11:57:39

标签: python

我编写了一些代码,它从csv文件中获取数据,将其存储在列表中,然后迭代数据,只返回我需要的信息。 我让它适用于单个列表:

# Import modules
import csv
import datetime
# import numpy as np
import matplotlib.pyplot as plt

# Time code (as slow to run)
tin = []
tout = []
tin = datetime.datetime.now() #tic
plt.close()

# Assign variables
pktime = []
pkey1 = []
pkey2 = []
pkey3 = []
pkey4 = []
pkey5 = []
pkey6 = []
pkeys=[pkey1, pkey2, pkey3, pkey4, pkey5, pkey6]
delt1 = []
delt2 = []
delt3 = []
delt4 = []
delt5 = []
delt6 = []
delts=[delt1, delt2, delt3, delt4, delt5, delt6]
pkey1full=[]
pkey2full=[]
pkey3full=[]
pkey4full=[]
pkey5full=[]
pkey6full=[]
pkeyfull=[pkey1full, pkey2full, pkey3full, pkey4full, pkey5full, pkey6full]


# Read in PK weight/deltaT/time values
with open('PKweight.csv') as pkweight:
    red = csv.reader(pkweight)
    for t, pk1, pk2, pk3, pk4, pk5, pk6, dt1, dt2, dt3, dt4, dt5, dt6 in red:

        pktime.append(datetime.datetime.strptime(t,'%H:%M:%S'))
        pkey1.append(float(pk1))
        pkey2.append(float(pk2))
        pkey3.append(float(pk3))
        pkey4.append(float(pk4))
        pkey5.append(float(pk5))
        pkey6.append(float(pk6))
        delt1.append(float(dt1))
        delt2.append(float(dt2))
        delt3.append(float(dt3))
        delt4.append(float(dt4))
        delt5.append(float(dt5))
        delt6.append(float(dt6))

#calculate the pkweight for each cell, then append it to pkey*full

def pkweight1_calc():
    i=1
    while i<=(len(pkey1)-1):
        if pkey1[i] == 0.0 and pkey1[i-1]!=0.0:
            pkey1full.append(pkey1[i-2])
        i+=1
    pkey1full.reverse()
    return pkey1full
pkweight1_calc()

我已经写了6次这段代码来完成每组数据的功能(1-6),但是我希望将它全部作为一个功能。我尝试在while循环中使用嵌套的while循环,但它只返回其中一个列表,无论j的初始值是什么:

def pkweight_calc():    
    i=1
    for j in range(0,5):
        while i<=(len(pkeys[j])-1):
            if (pkeys[j][i]) == 0.0 and (pkeys[j][i-1])!=0.0:
                pkeyfull[j].append(pkeys[j][i-2])
            i+=1
        pkeyfull[j].reverse()
pkweight_calc()

任何人都可以帮我吗?提前致谢!! 编辑 - 更新缩进,抱歉!

1 个答案:

答案 0 :(得分:0)

感谢您的帮助,我设法找到了可以帮助我的人。他不知道为什么要改变while循环

while i<=(len(pkeys[j])-1):

到for循环:

for i in range(2, len(pkeys[j])):

解决了它。不知道为什么,但确实如此!