簡體   English   中英

為什么我有“列表索引超出范圍”的提示,但列表中的值仍然存在?

[英]Why do I get 'list index out of range' although the times-list values are there?

介紹

首先,非常感謝您抽出寶貴時間來查看我的問題和代碼。 我知道我的編碼需要改進,但是與所有新事物一樣,它需要時間來完善。

背景

我正在使用不同的功能來執行以下操作:

  1. 導入多個文件(目前為3個)。 每個文件包含時間,壓力和無效列。
  2. 將列表存儲在字典中。 例如。 一個壓力字典中的所有壓力。
  3. 過濾壓力數據,並確保我仍然有相應數量的時間數據點(針對每個文件)。

我在主函數中調用這些函數。

問題

一切運行良好,直到我再次運行DataFilter函數中的時間循環。 但是,我確實檢查過我是否可以訪問字典中的三個壓力和時間列表。 為什么此時函數第二次運行時“索引超出范圍”: t=timeFROMtimes [i] 這是我得到的代碼輸出

#IMPORT LIBRARIES
import glob
import pandas as pd
import matplotlib.pyplot as plt, numpy as np
from scipy.interpolate import spline

#INPUT PARAMETERS
max_iter = 3 #maximum number of iterations
i = 0 #starting number of iteration
tcounter = 0
number_of_files = 3 #number of files in directory
sourcePath = 'C:\\Users\\*' #not displaying actual directory
list_of_source_files = glob.glob(sourcePath + '/*.TXT')
pressures = {} #initialize a dictionary
times ={} #initialize a dictionary

#GET SPECIFIC FILE & PRESSURE, TIME VALUES 
def Get_source_files(list_of_source_files,i):
    #print('Get_source_files')
    with open(list_of_source_files[i]) as source_file:
        print("file entered:",i+1)
        lst = [] 
        for line in source_file:
            lst.append([ float(x) for x in line.split()])
        time = np.array([ x[0] for x in lst]) #first row in file and make array
        void = np.array([ x[1] for x in lst]) #second row in file and make array
        pressure =(np.array([ x[2] for x in lst]))*-1 #etc. & change the sign of the imported pressure data
    return pressure,time

#SAVE THE TIME AND PRESSURE IN DICTIONARIES
def SaveInDictionary (Pressure,time,i):
    #print('SaveInDictionary')
    pressures[i]=[Pressure]
    times[i]=[time]
    return pressures,times

#FILTER PRESSURE DATA AND ADJUST TIME
def FilterData (pressureFROMpressures,timeFROMtimes,i):
    print('FilterData')
    t=timeFROMtimes [i]
    p=pressureFROMpressures[i]
    data_points=int((t[0]-t[-1])/-0.02) #determine nr of data points per column of the imported file
    filtered_pressure = [] #create an empty list for the filtered pressure
    pcounter = 0 #initiate a counter
    tcounter = 0
    time_new =[0,0.02] #these initial values are needed for the for-loop

    for j in range(data_points): 
        if p[j]<8: #filter out all garbage pressure data points above 8 bar
            if p[j]>0:
                filtered_pressure.append(p[j]) #append the empty list ofsave all the new pressure values in new_pressure
                pcounter += 1

    for i in range(pcounter-1):
        time_new[0]=0
        time_new[i+1]=time_new[i]+0.02 #add 0.02 to the previous value
        time_new.append(time) #append the time list
        tcounter += 1 #increment the counter
    del time_new[-1] #somehow a list of the entire time is formed at the end that should be removed
    return filtered_pressure, time_new

#MAIN!!
P = list()
while (i <= number_of_files and i!=max_iter):
    pressure,time = Get_source_files(list_of_source_files,i) #return pressure and time from specific file
    pressures, times = SaveInDictionary (pressure,time,i)#save pressure and time in the dictionaries
    i+=1 #increment i to loop
print('P1=',pressures[0])
print('P2=',pressures[1])
print('P3=',pressures[2])
print('t1=',times[0])
print('t2=',times[1])
print('t3=',times[2])

#I took this out of the main function to check my error:
for i in range(2):
    filtered_pressure,changed_time = FilterData(pressures[i],times[i],i)
    finalP, finalT = SaveInDictionary (filtered_pressure,changed_time,i)#save pressure and time in the dictionaries

在循環中,您已經退出了已經索引到times中的main函數,但是在

#I took this out of the main function to check my error:
for i in range(2):
    filtered_pressure,changed_time = FilterData(pressures[i],times[i],i)
    # Here you call FilterData with times[i]

但是在FilterData函數中,您在其中調用傳遞的變量timeFROMtimes ,然后使用i再次對其進行索引:

def FilterData (pressureFROMpressures,timeFROMtimes,i):
    print('FilterData')
    t=timeFROMtimes [i]  # <-- right here 

這似乎很奇怪。 嘗試刪除其中一個索引運算符( [i] ),也可以消除pressures

編輯

正如@strubbly所指出的那樣,在SaveInDictionary函數中分配[Pressure]值。 方括號表示一個包含一個元素的列表,即numpy數組Pressure 當您打印P1-3和t1-3時,在錯誤消息中,可以通過數組前面的開括號看到這一點。 要直接保存您的numpy數組,請松開括號:

def save_in_dictionary(pressure_array, time, i):
    pressures[i] = pressure_array
    times[i] = time
    return pressures, times

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM