0
我已經寫了一些代碼,它從csv文件中獲取數據,將它存儲在列表中,然後迭代僅返回我需要的信息的數據。 我是有工作單列表:嵌套while循環只迭代一次
# 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的inital值:
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()
誰能幫助我?提前致謝!! 編輯 - 更新縮進,對不起!
這是您在代碼中的實際縮進嗎?因爲正如書面它是一個無限循環。 – khelwood
也看看這行'pkey1full.append(pkey1 [i-2])',是不是它試圖訪問pkey1 [-1]'i = 1'? – Fallen
爲什麼你寫成一個無限循環。實際上你需要的是 –